刷題-力扣-6
阿新 • • 發佈:2021-01-10
6. Z 字形變換
題目連結
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/zigzag-conversion/
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
題目描述
將一個給定字串 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
示例 3:
輸入:s = "A", numRows = 1
輸出:"A"
提示:
- 1 <= s.length <= 1000
- s 由英文字母(小寫和大寫)、',' 和 '.' 組成
- 1 <= numRows <= 1000
題目分析
- 對比字串s和z字形,可以發現每一行相鄰的兩個元素之間存在關係。
- 在示例2中。第二行第一個元素“A”所在s中位置為1(從0算起),下一個元素的位置為:當前位置 + 2 * (行數 - 所處行數),再下一個元素位置為:當前位置 + 2 * (所處行號 - 1)
- 在2中每兩次為一個迴圈。
- 迴圈截至條件為s中不存在下一個元素,則終止當前行的迴圈。開始下一行的迴圈。
- 當所有行迴圈完成,程式結束,所得字串即為所求。
程式碼
class Solution { public: string convert(string s, int numRows) { if (numRows == 1) return s; int start = 2 * (numRows - 1); int end = 0; char str[1001]; int strIndex = 0; int nowE = 0; for (int e = 0; e < numRows; e++) { nowE = e; while (true) { if (nowE >= s.size()) { break; } if (start > 0) { str[strIndex] = s[nowE]; strIndex++; nowE = nowE + start; } if (nowE >= s.size()) { break; } if (end > 0) { str[strIndex] = s[nowE]; strIndex++; nowE = nowE + end; } } start = start - 2; end = end + 2; } str[strIndex] = '\0'; string strRes(str); return strRes; } };
用時92min