LeetCode -字符串“之”字形轉(zhuǎn)換
前言我們社區(qū)陸續(xù)會(huì)將顧毅(Netflix 增長(zhǎng)黑客,《iOS 面試之道》作者,ACE 職業(yè)健身教練。微博:@故胤道長(zhǎng)[1])的 Swift 算法題題解整理為文字版以方便大家學(xué)習(xí)與閱讀。
LeetCode 算法到目前我們已經(jīng)更新了 3 期,我們會(huì)保持更新時(shí)間和進(jìn)度(周一、周三、周五早上 9:00 發(fā)布),每期的內(nèi)容不多,我們希望大家可以在上班路上閱讀,長(zhǎng)久積累會(huì)有很大提升。
難度水平:中等
1. 描述
已知一個(gè)字符串 “PAYPALISHIRING” 在確定的行數(shù)上以 “之” 字形圖案書(shū)寫(xiě),如下所示:
- P A H N
- A P L S I I G
- Y I R
然后逐行閱讀獲得一個(gè)新的字符串:“PAHNAPLSIIGYIR”
- func convert(s: String, _ numRows: Int) -> String
已知一個(gè)字符串和行數(shù),在上述方法內(nèi)編寫(xiě)轉(zhuǎn)換的代碼。
2. 示例
示例 1
- 輸入:s = "PAYPALISHIRING", numRows = 3
- 輸出: "PAHNAPLSIIGYIR"
- 解釋?zhuān)?nbsp;
- P A H N
- A P L S I I G
- Y I R
示例 2
- 輸入:s = "PAYPALISHIRING", numRows = 4
- 輸出: "PINALSIGYAHRPI"
- 解釋?zhuān)?nbsp;
- 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
3. 答案
- class Solution {
- func convert(s: String, _ numRows: Int) -> String {
- if numRows == 1 {
- return s
- }
- var ret: [Character] = []
- var chars: [Character] = [Character](s.characters)
- let cnt = chars.count
- for i in 0..<numRows {
- let len = 2 * numRows - 2
- var index = i
- while index < cnt {
- ret.append(chars[index])
- if i != 0 && i != numRows - 1 {
- let tmpIndex = index + 2 * (numRows - i - 1)
- if tmpIndex < cnt {
- ret.append(chars[tmpIndex])
- }
- }
- index += len
- }
- }
- return String(ret)
- }
- }
- 主要思想:第一行和最后一行,循環(huán)長(zhǎng)度為 (2 * numRows - 2)對(duì)于它們之間的每一行,應(yīng)該插入另一個(gè)數(shù)字,index = index + 2 * (numRows - i - 1)
- 時(shí)間復(fù)雜度:O(log(n + m))
- 空間復(fù)雜度:O(1)
該算法題解的倉(cāng)庫(kù):LeetCode-Swift[2]
點(diǎn)擊前往 LeetCode[3] 練習(xí)
關(guān)于我們公眾號(hào)是由 Swift 愛(ài)好者共同維護(hù),我們會(huì)分享以 Swift 實(shí)戰(zhàn)、SwiftUI、Swift 基礎(chǔ)為核心的技術(shù)內(nèi)容,也整理收集優(yōu)秀的學(xué)習(xí)資料。歡迎關(guān)注公眾號(hào):Swift社區(qū),后臺(tái)點(diǎn)擊進(jìn)群,聯(lián)系我們獲取更多內(nèi)容。
參考資料
[1]@故胤道長(zhǎng): https://m.weibo.cn/u/1827884772
[2]LeetCode-Swift: https://github.com/soapyigu/LeetCode-Swift
[3]LeetCode: https://leetcode.com/problems/longest-palindromic-substring/