Palindrome check

A Palindrome is a word, phrase, or sequence that reads the same backward as forward.
Ex: RaceCar, madam, mom, level
We have two methods to check for a palindrome.

1. Reverse String Comparision:
If we reverse a string and compare it with the given string, then if both the strings are equal, we can say the given string is a palindrome.

func reversedString(input:String)->String{
    var reversed = ""
    
    for char in input{
        reversed = "\(char)" + reversed
    }
    
    return reversed
}


func isPalindrome(_ input :String)->Bool{
    let reversed = reversedString(input: input)
    return reversed == input
}
Time Complexity: θ(n)
Space Complexity: θ(n)

2. Character Comparision:
We'll start comparing the first character with the last character, if both are equal we'll increment the left index & decrement the right index until we cross the middle character. If we successfully pass the middle character then the given string is a Palindrome.


func isPalindrome(_ input:String)->Bool{
    var leftIndex = input.startIndex
    var rightIndex = input.index(before: input.endIndex)
    
    while leftIndex <= rightIndex {
        if input[leftIndex] != input[rightIndex]{
            return false
        }
        leftIndex = input.index(after: leftIndex)
        rightIndex = input.index(before: rightIndex)
    }
    
    return true
}
Time Complexity: O(n)
Space Complexity: O(1)

Comments

Popular posts from this blog

Swift Package Manager: Demystifying Targets and Libraries

IOS Simulator Crash report