Skip to content

Instantly share code, notes, and snippets.

@ahcode0919
Last active October 29, 2021 12:59
Show Gist options
  • Save ahcode0919/ac1e2edb3e6ade1d7ca742ae923e4383 to your computer and use it in GitHub Desktop.
Save ahcode0919/ac1e2edb3e6ade1d7ca742ae923e4383 to your computer and use it in GitHub Desktop.
A few ways to reverse a string in Swift
let word = "abcdefg"
//Using swift lib
String(word.characters.reverse()) //"gfedcba"
//Using char array and insert
func reverseString(wordToReverse: String) -> String {
guard wordToReverse.characters.count > 1 else {
return wordToReverse
}
var reversedWord = [Character]()
for char in wordToReverse.characters {
reversedWord.insert(char, atIndex: 0)
}
return String(reversedWord)
}
assert(reverseString(word) == "gfedcba")
//Swap in-place, using char array
func reverseString2(wordToReverse: String) -> String {
guard wordToReverse.characters.count > 1 else {
return wordToReverse
}
var newWord = Array(wordToReverse.characters)
let maxIndex = newWord.count - 1
for i in 0...maxIndex {
if i > maxIndex - i {
break
}
(newWord[i], newWord[maxIndex - i]) = (newWord[maxIndex - i], newWord[i])
}
return String(newWord)
}
assert(reverseString2(word) == "gfedcba")
@burhanaras
Copy link

burhanaras commented Oct 29, 2021

@jmohanr here is what you look for: Time complexity: O(N), Space comp. : O(N)

func reverseWithSpaces(of str: String) -> String {
    var newStr = [Character]()
    
    var lastIndexOffset = str.count - 1
    for char in str.enumerated() {
        if char.element == " " {
            newStr.insert(" ", at: 0)
        } else {
            let index = str.index(str.startIndex, offsetBy: lastIndexOffset)
            newStr.insert(str[index], at: 0)
            lastIndexOffset -= 1
        }
    }
    
    return String(newStr)
}

// Test

let apple = "I am apple"
let reversedApple = reverseWithSpaces(of: apple)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment