Skip to content

Instantly share code, notes, and snippets.

@junebash
Created January 15, 2020 16:23
Show Gist options
  • Save junebash/0a94dbd2afbddbdb8057720c1a75b56b to your computer and use it in GitHub Desktop.
Save junebash/0a94dbd2afbddbdb8057720c1a75b56b to your computer and use it in GitHub Desktop.
iOS11 Code Challenge (2020-01-15) - Reverse Only Letters
func reverseOnlyLetters(_ inputString: String) -> String {
let lettersReversed = [Character](
inputString.compactMap { char -> Character? in
return char.isLetter ? char : nil
}.reversed()
)
var outputCharacters = [Character](inputString)
var i = 0
while i < lettersReversed.count {
for j in 0..<outputCharacters.count {
if outputCharacters[j].isLetter {
outputCharacters[j] = lettersReversed[i]
i += 1
}
}
}
let outputString = String(outputCharacters)
return outputString
}
print(reverseOnlyLetters("ab-cd"))
print(reverseOnlyLetters("a-bC-dEf-ghIj"))
print(reverseOnlyLetters("Test1ng-Leet=code-Q!"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment