Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for palindrome in Swift using recursive definition

I like many of the features in Swift, but using manipulating strings are still a big pain in the ass.

func checkPalindrome(word: String) -> Bool {
    print(word)
    if word == "" {
        return true
    } else {
        if word.characters.first == word.characters.last {
            return checkPalindrome(word.substringWithRange(word.startIndex.successor() ..< word.endIndex.predecessor()))
        } else {
            return false
        }
    }
}

This code fails miserably whenever the string's length is an odd number. Of course I could make it so the first line of the block would be if word.characters.count < 2, but is there a way in Swift to get substrings and check easily?

Update I like many of the suggestions, but I guess the original question could be misleading a little, since it's a question about String more than getting the right results for the function.

For instance, in Python, checkPalindrome(word[1:-1]) would work fine for the recursive definition, whereas Swift code is much less graceful since it needs other bells and whistles.

like image 453
funct7 Avatar asked Dec 28 '15 07:12

funct7


People also ask

How do you check if a number is a palindrome?

A simple method for this problem is to first reverse digits of num, then compare the reverse of num with num. If both are same, then return true, else false.

What is palindrome number in Swift?

Approach 1 Convert to string (Accepted): Convert number to a string and then traverse from start and end and do a comparison if there is mismatch it means the number is not a palindrome. Single digit without a sign is always palindrome so we will return true for that case at the start.


2 Answers

return word == String(word.reversed())
like image 67
Gigi Avatar answered Sep 30 '22 17:09

Gigi


func isPalindrome(myString:String) -> Bool {
    let reverseString = String(myString.characters.reversed())
    if(myString != "" && myString == reverseString) {
        return true
    } else {
        return false
    }
}

print(isPalindrome("madam"))
like image 44
S.M.Moinuddin. Shuvo Avatar answered Sep 30 '22 16:09

S.M.Moinuddin. Shuvo