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;
    }
}
發佈了39 篇原創文章 · 獲贊 17 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章