5. Longest Palindromic Substring
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
class Solution {
public boolean isPalindrome(String text) {
int lastIndex = text.length() - 1;
int firstIndex = 0;
while (firstIndex <= lastIndex) {
if (text.charAt(firstIndex) != text.charAt(lastIndex)) {
return false;
}
++firstIndex;
--lastIndex;
}
return true;
}
public String longestPalindrome(String s) {
if (s == null || s.isEmpty()) {
return "";
}
int max = 1;
String maxString = s.substring(0,1);
for (int i = 0; i < s.length(); i++) {
for (int j = i + 1; j < s.length(); j++) {
String sub = s.substring(i, j + 1);
int length = sub.length();
boolean isp = isPalindrome(sub);
if (isp) {
if (max < length) {
max = length;
maxString = sub;
}
}
}
}
return maxString;
}
}