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
解题思路:
将每个字符串用不同的颜色标出来,原字符串可以看成由很多长度为(2*numRows-1)的颜色回文且两端重叠的区间组成,将回文区间的两端单独处理,所以外层循环控制回文区间颜色块到每一段的两端的距离,同时也决定了取得的字符串的顺序,然后将取出的字符串拼接起来就是要求得的最终串。
C
char* convert(char* s, int numRows) {
if(numRows==1){
return s;
}
--numRows;
int slen = strlen(s);
char *rs = (char*)malloc((slen+1)*sizeof(char));
int skip = 2*numRows;
int rslen = 0;
for(int i=0;i<slen;i+=skip){
rs[rslen++] = s[i];
}
for(int i=1;i<numRows;i++){
int j =0 ;
while(j<slen){
if(j-i>=0)rs[rslen++] = s[j-i];
if(j+i<slen)rs[rslen++] = s[j+i];
j += skip;
}
if(j-i<slen)rs[rslen++] = s[j-i];
}
for(int i=numRows;i<slen;i+=skip){
rs[rslen++] = s[i];
}
rs[rslen] = '\0';
return rs;
}
C++
class Solution {
public:
string convert(string s, int numRows) {
if(numRows==1){
return s;
}
--numRows;
int slen = s.size();
char *rs = (char*)malloc((slen+1)*sizeof(char));
int skip = 2*numRows;
int rslen = 0;
for(int i=0;i<slen;i+=skip){
rs[rslen++] = s[i];
}
for(int i=1;i<numRows;i++){
int j =0 ;
while(j<slen){
if(j-i>=0)rs[rslen++] = s[j-i];
if(j+i<slen)rs[rslen++] = s[j+i];
j += skip;
}
if(j-i<slen)rs[rslen++] = s[j-i];
}
for(int i=numRows;i<slen;i+=skip){
rs[rslen++] = s[i];
}
rs[rslen] = '\0';
return rs;
}
};
Java
class Solution {
public String convert(String s, int numRows) {
if(numRows==1){
return s;
}
--numRows;
int skip = 2*numRows;
int slen = s.length();
StringBuilder rs = new StringBuilder();
for(int i=0;i<slen;i+=skip){
rs.append(s.charAt(i));
}
for(int i=1;i<numRows;i++){
int j = 0;
while(j<slen){
if(j-i>=0)rs.append(s.charAt(j-i));
if(j+i<slen)rs.append(s.charAt(j+i));
j += skip;
}
if(j-i<slen)rs.append(s.charAt(j-i));
}
for(int i=numRows;i<slen;i+=skip){
rs.append(s.charAt(i));
}
return rs.toString();
}
}
Python
class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows==1:return s
numRows -= 1
slen = len(s)
rs = ""
skip = 2*numRows
for i in range(0,slen,skip):
rs = rs + s[i]
for i in range(1,numRows):
j = 0
while j < slen:
if j-i>=0:rs=rs+s[j-i]
if j+i<slen:rs=rs+s[j+i]
j += skip
if j-i<slen:rs=rs+s[j-i]
for i in range(numRows,slen,skip):
rs = rs + s[i]
return rs