將字符串按 Z 字形(N 字形)排列在指定行數中,然後按行讀取生成新字符串。例如 "PAYPALISHIRING",3 行排列:
P A H N A P L S I I G Y I R
按行讀取得:"PAHNAPLSIIGYIR"
觀察每行字符在原字符串中的索引規律:
2*(nRows-1)2*(nRows-1-i) 和 2*i直接按行輸出,無需構建二維數組:
class Solution {
public:
string convert(string s, int nRows) {
if (nRows <= 1) return s;
string ans;
int len = s.length();
for (int i = 0; i < nRows; ++i) {
int cur = i;
while (cur < len) {
ans += s[cur]; // 主字符
// 中間行添加對角字符
if (i != 0 && i != nRows-1) {
int diag = cur + 2 * (nRows - 1 - i);
if (diag < len) ans += s[diag];
}
cur += 2 * (nRows - 1); // 下一週期
}
}
return ans;
}
};
cycle = 2 * (nRows - 1)cyclecur 和 cur + 2*(nRows-1-i)diag < lenO(n),每個字符恰好訪問一次O(n),結果字符串輸入:"PAYPALISHIRING", 3 輸出:"PAHNAPLSIIGYIR" 輸入:"ABCD", 2 輸出:"ACBD" (A C / B D)