共计 1034 个字符,预计需要花费 3 分钟才能阅读完成。
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 = 3Output: “PAHNAPLSIIGYIR”
Example 2:Input: s = “PAYPALISHIRING”, numRows = 4Output: “PINALSIGYAHRPI”Explanation:
P I N
A L S I G
Y A H R
P I
难度:medium
题目:字符串 ”PAYPALISHIRING” 以之字形表法。
思路:数组索引遍历下加上减。
Runtime: 22 ms, faster than 80.40% of Java online submissions for ZigZag Conversion.
class Solution {
public String convert(String s, int numRows) {
if (1 == numRows) {
return s;
}
int idx = 0, signFlg = 1;
StringBuilder[] sbArray = new StringBuilder[numRows];
for (int i = 0; i < numRows; i++) {
sbArray[i] = new StringBuilder();
}
for (int i = 0; i < s.length(); i++) {
if (0 == idx) {
signFlg = 1;
}
sbArray[idx].append(s.charAt(i));
idx = (idx + signFlg) % numRows;
if ((numRows – 1) == idx) {
signFlg = -1;
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < numRows; i++) {
sb.append(sbArray[i]);
}
return sb.toString();
}
}