题目描述:
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"
.两种解法:
第一种是遍历s,将一个个字符写入vector<string>,最后将数组连起来输出。需要用一个变量来控制写入顺序。
第二种是直接找出规律,稍微写下就找的出来:步长STEP= 2 * nRows - 2,res+=s[(i / 2)*STEP + r]+s[(i / 2)*STEP + STEP - r],当然记得要判定边界条件。
代码如下,第一种方法96ms通过,第二种方法MLE,但代码没发现问题,在自己机子上跑也没问题,变量数明显应该比第一种方法少,不知为何MLE……仅供参考吧:
class Solution {
public:
string convert(string s, int nRows) {
vector<string> zz(nRows);
int j(0);
bool even(true);
for (int i = 0; i < s.length(); i++){
zz[j] += s[i];
if (even)
j++;
else
j--;
while ((even && (j >= nRows || j < 0)) || (!even && (j >= nRows - 1 || j <= 0))){
even = !even;
if (even)
j = 0;
else
j = nRows - 2;
}
}
string res;
for (int i = 0; i < nRows; i++)
res += zz[i];
return res;
}
};
class Solution {
public:
string convert(string s, int nRows) {
if (nRows >= s.length() || nRows <= 0)
return s;
int STEP = 2 * nRows - 2;
int N = s.length();
string res;
for (int r = 0; r < nRows; r++){
int i = 0;
while (1){
if ((i / 2)*STEP + r >= N)
break;
res += s[(i / 2)*STEP + r];
if ((i / 2)*STEP + STEP - r >= N)
break;
if (r != 0 && r != nRows - 1)
res += s[(i / 2)*STEP + STEP - r];
i += 2;
}
}
return res;
}
};