-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathLongestPalindromicSubstring.kt
58 lines (53 loc) · 1.47 KB
/
LongestPalindromicSubstring.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
* Given a string s, find the longest palindromic substring in s.
* You may assume that the maximum length of s is 1000.
*
* Example:
*
* Input: "babad"
*
* Output: "bab"
*
* Note: "aba" is also a valid answer.
* Example:
*
* Input: "cbbd"
*
* Output: "bb"
*
* Accepted.
*/
class LongestPalindromicSubstring {
fun longestPalindrome(s: String?): String? {
if (s == null || s.length <= 1) {
return s
}
var maxLength = 0
var startIndex = 0
for (index in 0 until s.length) {
var leftIndex = index
var rightIndex = index
while (leftIndex >= 0 && rightIndex < s.length && s[leftIndex] == s[rightIndex]) {
val current = rightIndex - leftIndex + 1
if (current > maxLength) {
maxLength = current
startIndex = leftIndex
}
leftIndex--
rightIndex++
}
leftIndex = index
rightIndex = index + 1
while (leftIndex >= 0 && rightIndex < s.length && s[leftIndex] == s[rightIndex]) {
val current = rightIndex - leftIndex + 1
if (current > maxLength) {
maxLength = current
startIndex = leftIndex
}
leftIndex--
rightIndex++
}
}
return s.substring(startIndex, maxLength + startIndex)
}
}