Skip to content

Commit

Permalink
[LeetCode] Add January 19.
Browse files Browse the repository at this point in the history
  • Loading branch information
pin3da authored Jan 19, 2021
1 parent f0dd82e commit c6c59f8
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions solved/LeetCode/Challenges/2020/January/19.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
class Solution {
private var seen = Array(1001) { Array(1001) {-1} }

private fun isPalindrome(s: String, i: Int, j: Int): Boolean {
if (j <= i) {
return true
}
if (seen[i][j] != -1) {
return seen[i][j] == 1
}
if (s[i] == s[j] && isPalindrome(s, i + 1, j - 1)) {
seen[i][j] = 1
return true
}
seen[i][j] = 0
return false
}

fun longestPalindrome(s: String): String {
var maxLen = 0
for (i in s.indices) {
for (j in i until s.length) {
if (isPalindrome(s, i, j)) {
maxLen = maxLen.coerceAtLeast(j - i)
}
}
}
for (i in s.indices) {
for (j in i until s.length) {
if (isPalindrome(s, i, j) && (j - i) == maxLen) {
return s.substring(i, j + 1)
}
}
}
error("answer not found.")
}
}

0 comments on commit c6c59f8

Please sign in to comment.