Valid Palindrome
1 min read

Valid Palindrome

Given a string, return whether or not it forms a palindrome ignoring case and non-alphabetical characters.
Note: a palindrome is a sequence of characters that reads the same forwards and backwards.

Ex: Given the following strings...

"level", return true
"algorithm", return false
"A man, a plan, a canal: Panama.", return true

1.  Using reversed()

Ignore non alphabetical characters using regex, remove case sensitivity and check for the reversed string equals actual.

Removing case senstivity is a trivial task, just use String functions lowerCase() or upperCase(), whichever you prefer.

Next task would be to ignore the alphabetical characters, we can use the regex to replace those. A good regex here would be """[\W+]""".Please check Regex  for details.

fun main() {
    var stringValue = "level"
   
    print(isPalindrome(stringValue))
}

fun isPalindrome(value: String): Boolean {
    val currentString = value.lowercase().replace("""[\W+]""".toRegex(), "")
    return currentString == currentString.reversed()
}
c

The isPalindrome function works by transforming the supplied string to lower case, then using the replace function with the needed regex. it uses == to see if the string value is equivalent to its reverse.

2.  Using For Loop

fun main() {
    var stringValue = "level"
   
    print(isPalindrome(stringValue))
}

fun isPalindrome(value: String): Boolean {
   val currentString = value.lowercase().replace("""[\W+]""".toRegex(), "")
   val length = currentString.length
   for(i in length/2 downTo(0)) {
       if(currentString[i] != currentString[length - i - 1]){
           return false
       }
   } 
   return true
}

Enjoying these posts? Subscribe for more