leetcode第6题——*ZigZag Conversion

题目

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 text, int nRows);
convert("PAYPALISHIRING", 3)  should return  "PAHNAPLSIIGYIR" .

思路

简单解释一下zigzag,就是把字符串原顺序012345……按下图所示排列并按行输出:


发现每一行中除斜行的字符其对应的下标为(0,1,2,3,6,7,8,9...),观察得到下标周期cycle=2*(numRows-1),如当numRows=4时,周期为6;而那几个处于斜行的字符,记前一个竖行的字符其下标为j,则斜行字符其下标为j+cycle-2*i,其中i为对应的行下标(0,1,2,...,numRows-1)。找到每一行的下标规律,按照字符串相加即可得到所求字符串。

代码

Python

class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        cycle = 2*(numRows - 1)
        strLen = len(s)
        res = ''
        if (strLen == 0) | (numRows < 2):
            return s
        for i in range(numRows):
            for j in range(i,strLen,cycle):
                res += s[j]
                if (i > 0) & (i < numRows - 1):
                    #首行和最后一行除外的其他要再加一个元素,下标为j + cycle - 2*i
                    zIndex = j + cycle - 2*i
                    if (zIndex < strLen):
                        res += s[zIndex]
        return res

Java

public class Solution {
    public String convert(String s, int numRows) {
       int strLen = s.length();
       if (numRows < 2 || strLen == 0)
    	   return s;
       int cycle = 2*(numRows - 1);
       String res = "";
       for(int i = 0;i < numRows;i++){
    	   for(int j = i;j < strLen;j += cycle){
    		   res += s.charAt(j);
    		   //除开首行和最后一行的其他行再添加s[index],index = j+2*(numRows-1)-2*i
    		   if(i > 0 && i < numRows-1){
    			   int zIndex = j + cycle - 2*i;
    			   if(zIndex < strLen)
    				   res += s.charAt(zIndex);
    		   }
    	   }
       }
       return res;
    }
}

你可能感兴趣的:(java,LeetCode,python)