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”.
这道题意思就是将给定的字符串转化为倒‘N’的图形,然后再逐行的打印出来。
参考这里
思路很简洁,以空间换时间,定义numRows行数的字符串,维护一个指针j指向第i行的字符串。
向下j从0到numRows循环赋值;
对角线上j从numRows-2(除去第一行和最后一行)到1循环赋值。
class Solution {
public:
string convert(string s, int numRows) {
if(s.size()==1||numRows<=1)return s;
string str[numRows];
int i=0,j;
while(i<s.size()){
for(j=0;j<numRows&&i<s.size();j++)str[j]+=s[i++];
for(j=numRows-2;j>0&&i<s.size();j--)str[j]+=s[i++];
}
string ss="";
for(j=0;j<numRows;j++)ss+=str[j];
return ss;
}
};
以上代码能通过,但有一个问题不太清楚,就是在while循环中为什么还要加上i小于s.size()的判定。
试了一下没加上的话,会出现Output Limited Exceed,不太清楚。