Last active
September 15, 2023 23:40
-
-
Save lingoslinger/726fec20e40000bccd0c7678e2da2653 to your computer and use it in GitHub Desktop.
Swift: Palindrome with bonus reversed() function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// I publicly share any answers to "coding challenges" I receive as a part of the interview process | |
// copy/paste this into an Xcode playground or the code challenge repl of choice | |
// Write a function in Swift that checks if a given string is a palindrome (reads the same forwards and backwards), | |
// ignoring whitespace and punctuation. | |
func palindrome(_ input: String) -> Bool { | |
return input == String(input.reversed()) | |
} | |
// there's also the extension version | |
extension String { | |
func isPalindrome() -> Bool { | |
return self == String(self.reversed()) | |
} | |
} | |
// if you are told specifically to not use the "reversed()" function, you could question why you want to work at a place | |
// that doesn't think the built-in libraries are good enough, or you could use the following function: | |
// this is also for the case where they tell you not to use swapAt( _, _) and is generally considered the fastest way to | |
// reverse a string without a library function | |
func myReverse(_ input: String) -> String { | |
var characters = Array(input) | |
var left = 0 | |
var right = characters.count - 1 | |
while left < right { | |
let temp = characters[left] | |
characters[left] = characters[right] | |
characters[right] = temp | |
left += 1 | |
right -= 1 | |
} | |
return String(characters) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment