题目:
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
Example 3:
Input: s = "A", numRows = 1
Output: "A"
Constraints:
1 <= s.length <= 1000
s
consists of English letters (lower-case and upper-case),','
and'.'
.1 <= numRows <= 1000
解法:
一、高赞的解法,创建nRows个StringBuffer,从头开始遍历字符串s,每个字符放到对应的StringBuffer里。最后把StringBuffer按顺序拼在一起。
这种方法更直观,但是占用的空间比较多,需要额外的几个StringBuffer。
public String convert(String s, int nRows) {
char[] c = s.toCharArray();
int len = c.length;
StringBuffer[] sb = new StringBuffer[nRows];
for (int i = 0; i < sb.length; i++) sb[i] = new StringBuffer();
int i = 0;
while (i < len) {
for (int idx = 0; idx < nRows && i < len; idx++) // vertically down
sb[idx].append(c[i++]);
for (int idx = nRows-2; idx >= 1 && i < len; idx--) // obliquely up
sb[idx].append(c[i++]);
}
for (int idx = 1; idx < sb.length; idx++)
sb[0].append(sb[idx]);
return sb[0].toString();
}
二、高赞的python解法,比较巧妙
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1 or numRows >= len(s):
return s
#初始化numRows个数组来放字符
L = [''] * numRows
index, step = 0, 1
for x in s:
L[index] += x
#最关键的,如果index==0,说明是在第一行,则step设为1,存的L[index]越来越大
#如果index==numRows-1,说明到了最后一行,则step设为-1,存的L[index]越来越小
if index == 0:
step = 1
elif index == numRows -1:
step = -1
index += step
return ''.join(L)
三、我自己的解法,不需要多个数组,根据位置来依次取字符
def convert(self, s: str, numRows: int) -> str:
if(numRows==1):
return s
result=''
length= len(s)
p=0
#第一层,i=0
while(p<length):
result+=s[p]
p+=2*numRows-2
#第二层到倒数第二层
for i in range(1,numRows-1):
p=i
interval=(numRows-1-i)*2
while(p+interval<length):
result+=s[p]
result+=s[p+((numRows-1-i)*2)]
p+=2*numRows-2
if(p<length):
result+=s[p]
#最后一层
p=numRows-1
while(p<length):
result+=s[p]
p += 2 * numRows - 2
return result