—— write for my baby, mua
[题目]
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"
.
[中文翻译]
字符串"PAYPALISHIRING"
写成给定行数的ZigZag模式如下:(为了更好的可读性,你可能需要以固定字体显示这个模式)
P A H N A P L S I I G Y I R然后将该模式按行读:
"PAHNAPLSIIGYIR"
给定字符串和行数,编写代码完成这个转换:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3)
返回
"PAHNAPLSIIGYIR"
。
[解题思路]
zigZag模式,即将原来的字符串,按下图方式依次排列。
图1. ZigZag模式
O(M+N) M=len(text), N=nRows
如果nRows<=1,则直接返回text
否则,创建N个字符串,分别表示ZigZag模式的N行。遍历text的字符,将字符循环往复地插入N个字符串中,可以用一个指针(整数)表示当前字符要插入第几个字符串。
最后,将N个字符串连接,返回结果。
[C++代码]
class Solution {
public:
string convert(string s, int numRows) {
if (numRows <= 1)
return s;
string* line = new string[numRows];
int index = 0, dircetion = 1, lineIndex = 0;
while (index < s.size()) {
if (lineIndex < 0) {
lineIndex = 1;
dircetion = -dircetion;
}
else if (lineIndex >= numRows) {
lineIndex = numRows - 2;
dircetion = -dircetion;
}
line[lineIndex] = line[lineIndex] + s.at(index);
index++;
lineIndex += dircetion;
}
string res = "";
for (int i = 0; i < numRows; i++)
res = res + line[i];
return res;
}
};