-
Notifications
You must be signed in to change notification settings - Fork 64
/
Solution2.java
36 lines (30 loc) · 899 Bytes
/
Solution2.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
public class Solution {
public String longestPalindrome(String s) {
if (s.length() <= 1) {
return s;
}
int maxLen = 1;
String maxStr = s.substring(0, 1);
for (int i = 0; i < s.length(); i++) {
for (int j = i + maxLen; j <= s.length(); j++) {
if (j - i > maxLen && isPalindrome(s.substring(i, j))) {
maxLen = j - i;
maxStr = s.substring(i, j);
}
}
}
return maxStr;
}
private boolean isPalindrome(String str) {
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}