Home > front end >  Slice() nested for loop values i and j Kotlin
Slice() nested for loop values i and j Kotlin

Time:12-06

I'm wanting to slice a range which I can do in Javascfript but am struggling in kotlin.

my current code is:

internal class blah {
    fun longestPalindrome(s: String): String {
        var longestP = ""
        for (i in 0..s.length) {
            for (j in 1..s.length) {
                var subS = s.slice(i, j)
                if (subS === subS.split("").reversed().joinToString("") && subS.length > longestP.length) {
                    longestP = subS
            }
        } 
    } 
        return longestP
}

and the error I get is:

Type mismatch.
Required:
IntRange
Found:
Int

Is there a way around this keeping most of the code I have?

CodePudding user response:

As the error message says, slice wants an IntRange, not two Ints. So, pass it a range:

var subS = s.slice(i..j)

By the way, there are some bugs in your code:

  • You need to iterate up to the length minus 1 since the range starts at 0. But the easier way is to grab the indices range directly: for (i in s.indices)
  • I assume j should be i or bigger, not 1 or bigger, or you'll be checking some inverted Strings redundantly. It should look like for (j in i until s.length).
  • You need to use == instead of ===. The second operator is for referential equality, which will always be false for two computed Strings, even if they are identical.
  • I know this is probably just practice, but even with the above fixes, this code will fail if the String contains any multi-code-unit code points or any grapheme clusters. The proper way to do this would be by turning the String into a list of grapheme clusters and then performing the algorithm, but this is fairly complicated and should probably rely on some String processing code library.

CodePudding user response:

class Solution {
    fun longestPalindrome(s: String): String {
        var longestPal = ""
        for (i in 0 until s.length) {
            for (j in i   1..s.length) {
                val substring = s.substring(i, j)
                if (substring == substring.reversed() && substring.length > longestPal.length) {
                    longestPal = substring
                }
            }
        }
        return longestPal
    }
}

This code is now functioning but unfortunately is not optimized enough to get through all test cases.

  • Related