Qt當前工作目錄
阿新 • • 發佈:2021-01-12
技術標籤:LeetCode
6. Z 字形變換
題目描述
將一個給定字串 s 根據給定的行數 numRows ,以從上往下、從左到右進行 Z 字形排列。
比如輸入字串為 “PAYPALISHIRING” 行數為 3 時,排列如下:
P A H N
A P L S I I G
Y I R
之後,你的輸出需要從左往右逐行讀取,產生出一個新的字串,比如:"PAHNAPLSIIGYIR"
。
請你實現這個將字串進行指定行數變換的函式:
string convert(string s, int numRows);
示例1
輸入:s = "PAYPALISHIRING", numRows = 3 輸出:"PAHNAPLSIIGYIR"
示例2
輸入:s = "PAYPALISHIRING", numRows = 4
輸出:"PINALSIGYAHRPI"
解釋:
P I N
A L S I G
Y A H R
P I
提示:
- 1 ≤ s . l e n g t h ≤ 1000 1 \le s.length \le 1000 1≤s.length≤1000
s
由英文字母(小寫和大寫)、','
和'.'
組成- 1 ≤ n u m R o w s ≤ 1000 1 \le numRows \le 1000 1≤numRows≤1000
題解:
找規律。
按某種形狀列印字元的題目,一般通過手畫小圖找規律來做。
0 6 12
1 5 7 11 ..
2 4 8 10
3 9
從中我們發現,對於行數是 n n n 的情況:
- 對於第一行和最後一行,是公差為 2 ( n − 1 ) 2(n−1) 2(n−1) 的等差數列,首項是 0 0 0 和 n − 1 n−1 n−1;
- 對於第
i
i
i 行
(
0
<
i
<
n
−
1
)
(0<i<n−1)
(0<i<n−1),是兩個公差為
2
(
n
−
1
)
2(n−1)
2(n−1) 的等差數列交替排列,首項分別是
i
i
i 和
2
n
−
i
−
2
2n−i−2
所以我們可以從上到下,依次列印每行的字元。
時間複雜度分析:每個字元遍歷一遍,所以時間複雜度是 O ( n ) O(n) O(n).
程式碼:
class Solution {
public:
string convert(string& s, int numRows) {
if ( numRows == 1 ) return s;
int len = s.length();
string ret;
ret.resize(len);
int idx = 0;
int t = (numRows - 1) << 1;
for ( int i = 0; i < numRows; ++i ) {
if ( !i || i == numRows - 1 ) {
for ( int j = i; j < len; j += t )
ret[idx++] = s[j];
} else {
for ( int j = i, k = t - i; j < len || k < len; j += t, k += t ) {
if ( j < len ) ret[idx++] = s[j];
if ( k < len ) ret[idx++] = s[k];
}
}
}
return ret;
}
};
/*
時間:8ms,擊敗:94.87%
記憶體:8.1MB,擊敗:95.16%
*/