題目
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 RAnd 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……按下圖所示排列並按行輸出:
代碼
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;
}
}