zl程序教程

您现在的位置是:首页 >  其他

当前栏目

LeetCode - #6 字符串“之”字形转换

2023-03-20 15:00:02 时间

前言

我们社区陆续会将顾毅(Netflix 增长黑客,《iOS 面试之道》作者,ACE 职业健身教练。微博:@故胤道长[1])的 Swift 算法题题解整理为文字版以方便大家学习与阅读。

LeetCode 算法到目前我们已经更新了 3 期,我们会保持更新时间和进度(周一、周三、周五早上 9:00 发布),每期的内容不多,我们希望大家可以在上班路上阅读,长久积累会有很大提升。

不积跬步,无以至千里;不积小流,无以成江海。如果大家有建议和意见欢迎在文末留言,我们会尽力满足大家的需求。

难度水平:中等

1. 描述

已知一个字符串 “PAYPALISHIRING” 在确定的行数上以 “之” 字形图案书写,如下所示:

P   A   H   N
A P L S I I G
Y   I   R

然后逐行阅读获得一个新的字符串:“PAHNAPLSIIGYIR”

func convert(s: String, _ numRows: Int) -> String 

已知一个字符串和行数,在上述方法内编写转换的代码。

2. 示例

示例 1

输入:s = "PAYPALISHIRING", numRows = 3
输出: "PAHNAPLSIIGYIR"
解释: 
P   A   H   N
A P L S I I G
Y   I   R

示例 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

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)
    }
}
  • 主要思想:第一行和最后一行,循环长度为 (2 * numRows - 2)对于它们之间的每一行,应该插入另一个数字,index = index + 2 * (numRows - i - 1)
  • 时间复杂度:O(log(n + m))
  • 空间复杂度:O(1)

该算法题解的仓库:LeetCode-Swift[2]

点击前往 LeetCode[3] 练习

关于我们

公众号是由 Swift 爱好者共同维护,我们会分享以 Swift 实战、SwiftUI、Swift 基础为核心的技术内容,也整理收集优秀的学习资料。

参考资料

[1]@故胤道长: https://m.weibo.cn/u/1827884772

[2]LeetCode-Swift: https://github.com/soapyigu/LeetCode-Swift

[3]LeetCode: https://leetcode.com/problems/longest-palindromic-substring/