Task is simply to write the classic isPalindrom-function.
Here's my implementation:
func isStringPalindrom(str: String) -> Bool {
let lcStr = str.lowercased()
var i = 0
let aChars = Array(lcStr)
while i < (lcStr.count / 2) {
if aChars[i] != aChars[aChars.count - (i + 1)] {
return false
}
i += 1
}
return true
}
// Samples (provided with the exercise)
print(isStringPalindrom(str: "rotator")) // Should return true
print(isStringPalindrom(str: "Rats live on no evil star")) // Should return true
print(isStringPalindrom(str: "Never odd or even")) // Should return false
print(isStringPalindrom(str: "Hello, world")) // Should return false
// Own ideas
print(isStringPalindrom(str: "Anna"))
print(isStringPalindrom(str: "Otto"))
print("Otxto: \(isStringPalindrom(str: "Otxto"))")
print(isStringPalindrom(str: "Tacocat"))
print(isStringPalindrom(str: "Tacoxcat"))
All tests work as expected. Therefore I think it's formally correct.
But could it become improved concerning algorithm and naming?
lcStr
, and you don't have to lowercase all letters.lcStr.count
is O(n). \$\endgroup\$