TLE is there a quicker way to write this in Swift?


  • 0
    R
    class Solution {
        func reverseString(s: String) -> String {
            var stringLength = s.characters.count
            var returnString = "" // S isn't mutable in swift.
        
            for var ndx = 0; ndx < stringLength; ndx++ {
                returnString.insert(s[s.startIndex.advancedBy(ndx)], atIndex: returnString.startIndex)
            }
            
            return returnString
        }
    }
    

    That is without using the reverse method because below is of course a solution:

    class Solution {
        func reverseString(s: String) -> String {
           return String(s.characters.reverse())
        }
    }

  • 0
    J

    for swift 3:

        var ret = s
    
        if ret.characters.count <= 1 {
            return ret
        }
        
        var leftIndex = ret.startIndex
        var rightIndex = ret.index(before: ret.endIndex)
        while rightIndex > leftIndex {
            let leftStr = String(ret[leftIndex])
            let rightStr = String(ret[rightIndex])
            ret.replaceSubrange(leftIndex...leftIndex, with: rightStr)
            ret.replaceSubrange(rightIndex...rightIndex, with: leftStr)
    
            leftIndex = ret.index(after: leftIndex)
            rightIndex = ret.index(before: rightIndex)
        }
    
        return ret

Log in to reply
 

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