Question
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
My Answer
class Solution {
public String convert(String s, int numRows) {
if (numRows <= 1) {
return s;
}
// 初始化
StringBuilder[] sb = new StringBuilder[numRows];
for (int i = 0; i < numRows; i++) {
sb[i] = new StringBuilder("");
}
// 遍历数据,写入sb中
// true向下走,false向上走
boolean flag = true;
int index = 0;
for (int i = 0; i < s.length(); i++) {
sb[index].append(s.charAt(i));
// 从第一行,向下走
if (index == 0) {
flag = true;
}
// 最后一行,往上走
if (index == numRows - 1) {
flag = false;
}
if (flag) {
index++;
} else {
index--;
}
}
// 组装
StringBuilder result = new StringBuilder("");
for (StringBuilder temp : sb) {
result.append(temp);
}
return result.toString();
}
}
您可以选择一种方式赞助本站
支付宝扫一扫赞助
微信钱包扫描赞助
赏