Given string is Palindrome or not
Code
func isPalindrome(_ string: String) -> Bool {
let characters = Array(string.lowercased())
var left = 0
var right = characters.count - 1
while left < right {
if characters[left] != characters[right] {
return false
}
left += 1
right -= 1
}
return true
}
Example
// Example usage
print(isPalindrome("mom")) // true
print(isPalindrome("Neveroddoreven")) // true
print(isPalindrome("test")) // false
Output
Code
func isPalindromeNew(_ input: String) -> Bool {
let sanitizedInput = input.lowercased().replacingOccurrences(of: "[^a-z0-9]", with: "", options: .regularExpression)
return sanitizedInput == String(sanitizedInput.reversed())
}
Example
print(isPalindromeNew("racecar")) // true
print(isPalindromeNew("level")) // true
print(isPalindromeNew("hello")) // false
print(isPalindromeNew("A man, a plan, a canal: Panama")) // true