-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSolution.java
50 lines (38 loc) · 1.24 KB
/
Solution.java
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
/*
* 5. Longest Palindromic Substring
* https://leetcode.com/problems/longest-palindromic-substring/
* */
class Solution {
public String longestPalindrome(String s) {
int maxLength = 0;
String result = "";
for (int i = 0; i < s.length(); i++) {
int start = i;
int end = i;
while (end < s.length() && start >= 0 && s.charAt(start) == s.charAt(end)) {
start -= 1;
end += 1;
}
if (end - start > maxLength) {
maxLength = end - start;
result = s.substring(start + 1, end);
}
start = i;
end = i + 1;
while (end < s.length() && start >= 0 && s.charAt(start) == s.charAt(end)) {
start -= 1;
end += 1;
}
if (end - start > maxLength) {
maxLength = end - start;
result = s.substring(start + 1, end);
}
}
return result;
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.longestPalindrome("babad"));
System.out.println(solution.longestPalindrome("cbbd"));
}
}