美文网首页Swift algorithm practice
Swift 4.2 ZigZag Conversion

Swift 4.2 ZigZag Conversion

作者: d1497e8e780a | 来源:发表于2019-01-23 15:44 被阅读5次

Swift 4.2

class Solution {
  func convert(_ s: String, _ numRows: Int) -> String {
    guard numRows > 1 else { return s }
    var characters = Array(s)
    var str = ""
    
    for row in 0...numRows - 1 {
      var i = 0
      var index = 2 * i * (numRows - 1) + row
      
      while index < characters.count {
        str.append(characters[index])
        i += 1
        let leftIndex = 2 * i * (numRows - 1) - row
        index = 2 * i * (numRows - 1) + row
        if row > 0 {
          if leftIndex < characters.count, row != (numRows - 1) {
            str.append(characters[leftIndex])
          }
        }
        
      }
    }
    
    return str
  }
}

相关文章

网友评论

    本文标题:Swift 4.2 ZigZag Conversion

    本文链接:https://www.haomeiwen.com/subject/artsjqtx.html