Home > Blockchain >  tried check valid palindrom string problem solving using kotlin but there is one of the testcase is
tried check valid palindrom string problem solving using kotlin but there is one of the testcase is

Time:08-14

this is the problem A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.

Given a string s, return true if it is a palindrome, or false otherwise.

Example 1:

Input: s = "A man, a plan, a canal: Panama" Output: true Explanation: "amanaplanacanalpanama" is a palindrome. Example 2:

Input: s = "race a car" Output: false Explanation: "raceacar" is not a palindrome.

myCode

class Solution {
      fun isPalindrome(s:String):Boolean {
    var s1 = s.toLowerCase()
    var myStringBuilder = StringBuilder()
    var n = s1.length-1
    var n1=myStringBuilder.length

    for ( i in 0..n) {
        if (Character.isLetterOrDigit(s1[i])) {
            myStringBuilder.append(s1[i])
        }
    }
     for( i in 0 .. (n1/2)-1){
            if(myStringBuilder[i] != myStringBuilder[n1-i-1]){
                return false
            }
     } 
        return true
}
}

the first case passed but this is not passed as per the result Input: s = "race a car result true expected is false

CodePudding user response:

You can use this simple solution.

fun isPalindrome(s:String):Boolean {
    val str = s.filter { it.isLetterOrDigit() }.lowercase()
    for (i in 0..str.length/2 ){
        if (str[i]!=str[str.length-i-1])
            return false
    }
    return true
}

CodePudding user response:

You're initialising n1 too early:

// create an -empty- StringBuilder
var myStringBuilder = StringBuilder()
...
// since it's empty, n1 == 0
var n1=myStringBuilder.length

You're setting it to the length of the StringBuilder contents before you've actually put anything in it. This is a simple value you're setting, it's not a reference to the length getter that will give the current value when you access it. You set it once and that's its value forever.

So your last loop, the one that checks if it's a palindrome or not, never actually runs:

// since n1 is 0, this is for (i in 0..0)
for( i in 0 .. (n1/2)-1){

You can fix it by initialising n1 when you've finished adding your content to the StringBuilder, so you can get its final length:

for ( i in 0..n) {
    if (Character.isLetterOrDigit(s1[i])) {
        myStringBuilder.append(s1[i])
    }
}

// StringBuilder is complete, grab its final length
var n1 = myStringBuilder.length

// now you can use it
for (i in 0..(n1/2)-1) {

Just fyi, there's also an until operator that works like .. except it doesn't include the last value of the range. So you can write

for (i in 0 until (n1/2))

if you want!

  • Related