forked from kdn251/interviews
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestPalindromicSubstring.java
More file actions
42 lines (34 loc) · 1.08 KB
/
LongestPalindromicSubstring.java
File metadata and controls
42 lines (34 loc) · 1.08 KB
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
//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"
class LongestPalindromicSubstring {
public String longestPalindrome(String s) {
if(s == null || s.length() == 0) {
return "";
}
String longestPalindromicSubstring = "";
for(int i = 0; i < s.length(); i++) {
for(int j = i + 1; j <= s.length(); j++) {
if(j - i > longestPalindromicSubstring.length() && isPalindrome(s.substring(i, j))) {
longestPalindromicSubstring = s.substring(i, j);
}
}
}
return longestPalindromicSubstring;
}
public boolean isPalindrome(String s) {
int i = 0;
int j = s.length() - 1;
while(i <= j) {
if(s.charAt(i++) != s.charAt(j--)) {
return false;
}
}
return true;
}
}