Leetcode 6

2018-07-23  本文已影响0人  张桢_Attix

Problem Description

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

string convert(string s, int numRows);
Example 1:

Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:

Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:

P I N
A L S I G
Y A H R
P I

Java:

class Solution {
    public String convert(String s, int numRows) {
        if (numRows == 1) return s;
        char[] cs = s.toCharArray();
        StringBuilder res = new StringBuilder();
        
        for (int i = 0, gap = (numRows-1) * 2; i < numRows; i++) {
            for (int j = i, innerGap = (numRows-i-1) * 2; j < cs.length; j += gap) {
                res.append(cs[j]);
                if (i > 0 && i < numRows - 1 && j + innerGap < cs.length) {
                    res.append(cs[j + innerGap]);
                }
            }
        }
        return res.toString();
    }
}

Python:

class Solution:
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if numRows == 1:
            return s
        
        reses = [''] * numRows
        cr, inc = 0, 1
        for c in s:
            reses[cr] = reses[cr] + str(c)
            cr += inc
            if cr == 0:
                inc = 1
            elif cr == numRows - 1:
                inc = -1
        res = ''
        for r in reses:
            res += r
        return res
上一篇下一篇

猜你喜欢

热点阅读