问题描述
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"
.
题目链接:
思路分析
将一个string根据规定的行数输出类似拉链结构的新字符串。
这个题的难度在于没给出清晰的定义——什么是zigzag。真正的定义应该是偶数列的行数比奇数列行数少2,居中对齐。所以我们的做法是使用一个string的数组,按照顺序把字符放到应放的位置,然后将每一行的结果拼起来就可以了。
使用指针i来遍历原字符串,奇数列的操作就是在i<n && j<numRows时,顺序将字符塞进每一行;偶数行则是倒叙将字符放进第numRows - 2行和第1行中。需要注意,当numRows = 2时,偶数行将为空,即不执行操作。
代码
java
class Solution {
public String convert(String s, int numRows) {
if (numRows == 1) return s;
List<StringBuilder> rows = new ArrayList<>();
for (int i = 0; i < Math.min(numRows, s.length()); i++)
rows.add(new StringBuilder());
int curRow = 0;
boolean goingDown = true;
for (char c : s.toCharArray()) {
rows.get(curRow).append(c);
if (curRow == 0 || curRow == numRows - 1) goingDown = !goingDown;
curRow += goingDown ? -1 : 1;
}
StringBuilder ret = new StringBuilder();
for (StringBuilder row : rows) ret.append(row);
return ret.toString();
}
}
class Solution {
public:
string convert(string s, int numRows) {
vector<string> vs(numRows, "");
int n = s.length(), i = 0;
while (i < n){
for (int j = 0; j < numRows && i < n; j++){
vs[j].push_back(s[i++]);
}
for (int j = numRows - 2; j > 0 && i < n; j--){
vs[j].push_back(s[i++]);
}
}
string result = "";
for (string s:vs)
result += s;
return result;
}
};
时间复杂度:
O
(
n
)
O(n)
O(n)
空间复杂度:
O
(
n
)
O(n)
O(n)
反思
对于zigzag的定义不明确,因此无计可施。