Skip to content

Commit 1fb30da

Browse files
committed
Time: 215 ms (71.29%), Space: 40.7 MB (13.52%) - LeetHub
1 parent e1ff082 commit 1fb30da

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class Solution {
2+
private fun getPalindromeFrom(start: Int, end: Int, s: String, indices: IntRange): Pair<Int, Int> {
3+
var nextStart = start
4+
var nextEnd = end
5+
while (nextStart in indices &&
6+
nextEnd in indices &&
7+
s[nextStart] == s[nextEnd]
8+
) {
9+
--nextStart
10+
++nextEnd
11+
}
12+
13+
return nextStart + 1 to nextEnd - 1
14+
}
15+
16+
fun longestPalindrome(s: String): String {
17+
val indices = s.indices
18+
19+
var maxRange = 0..0
20+
var maxLength = 1
21+
22+
fun getPalindromeFrom(start: Int, end: Int) =
23+
getPalindromeFrom(start, end, s, indices)
24+
25+
for (i in indices) {
26+
listOf(
27+
getPalindromeFrom(i, i),
28+
getPalindromeFrom(i, i + 1),
29+
).forEach { (start, end) ->
30+
val length = end - start + 1
31+
if (length > maxLength) {
32+
maxLength = length
33+
maxRange = start..end
34+
}
35+
}
36+
37+
}
38+
39+
return s.slice(maxRange)
40+
}
41+
}

0 commit comments

Comments
 (0)