Swift Solution


  • 0
    L
        
        func convert(_ s: String, _ numRows: Int) -> String {
            
            if numRows == 1 {
                
                return s
            }
            
            //initalize array to store character for each row
            var arr = [[Character]]()
            
            for i in 0...numRows - 1 {
                
                arr.append([Character]())
            }
            var newStr = ""
            
            //start from first row
            var currentRow = 0
            
            var diff = 1
            
            for charactor in s {
                
                arr[currentRow].append(charactor)
                
                if (currentRow == numRows - 1 && diff == 1) || (currentRow == 0 && diff == -1){
                    
                    diff = -diff
                }
                
                //move down/up one row per time
                currentRow = currentRow + diff
            }
            
            for charArr in arr {
                
                newStr = newStr + String(charArr)
            }
            
            return newStr
        }
    }```

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.