2014年3月15日星期六
LeetCode - 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, and there exists one unique longest palindromic substring.
public class Solution {
public String longestPalindrome(String s) {
int len = s.length();
boolean palin[][] = new boolean[len][len];
String maxStr = "";
for(int i=0;i<len;i++) {
for(int j=i;j>=0;j--) {
palin[j][i] = s.charAt(j)==s.charAt(i) && (j+1>=i-1 || palin[j+1][i-1]);
if(palin[j][i] && i-j+1>maxStr.length()) {
maxStr = s.substring(j, i+1);
}
}
}
return maxStr;
}
}
public class Solution {
public String longestPalindrome(String s) {
if(s==null || s.length()<=1) return s;
String maxS = "";
for(int i=0;i<s.length();i++) {
maxS = expand(s, i, i, maxS);
// if(i!=s.length()-1)
maxS = expand(s, i, i+1, maxS);
}
return maxS;
}
private String expand(String str, int s, int e, String maxS) {
while(s>=0 && e<str.length() && str.charAt(s)==str.charAt(e)) {
s--;
e++;
}
if( e-s-1 > maxS.length() ) {
maxS = str.substring(s+1, e);
}
return maxS;
}
}
class Solution {
public:
string longestPalindrome(string s) {
string maxP = "";
for(int i=0;i<s.length();i++) {
expand(s, i, i+1, maxP);
expand(s, i-1, i+1, maxP);
}
return maxP;
}
void expand(const string s, int start, int end, string &maxP) {
while(start>=0 && end<s.length() && s[start]==s[end]) {
start --;
end ++;
}
int len = end-start-1;
if(len>maxP.length()) {
maxP = s.substr(start+1, end-start-1);
}
}
};
class Solution {
public:
string longestPalindrome(string s) {
int min_start = 0, max_len = 1;
for (int i = 0; i < s.size();) {
int start = i, end = i;
while (end < s.size()-1 && s[end+1] == s[end]) {
end++; // Skip duplicate characters.
}
//i = end+1;
i++;
while (end < s.size()-1 && start > 0 && s[end + 1] == s[start - 1]) {
end++;
start--;
} // Expand.
int new_len = end - start + 1;
if (new_len > max_len) {
min_start = start;
max_len = new_len;
}
}
return s.substr(min_start, max_len);
}
};
==========
public class Solution {
public String longestPalindrome(String s) {
if (s == null || s.length() <= 1) {
return s;
}
int maxLen = 1;
String res = s.substring(0, 1);
for (int i = 1; i < s.length(); i++) {
String s1 = getPalindrome(s, i, i);
if (s1.length() > maxLen) {
res = s1;
maxLen = s1.length();
}
if (s.charAt(i) == s.charAt(i - 1)) {
String s2 = getPalindrome(s, i - 1, i);
if (s2.length() > maxLen) {
res = s2;
maxLen = s2.length();
}
}
}
return res;
}
private String getPalindrome(String str, int s, int e) {
while (s > 0 && e < str.length() - 1 && str.charAt(s - 1) == str.charAt(e + 1)) {
s--;
e++;
}
return str.substring(s, e + 1);
}
}
订阅:
博文评论 (Atom)
没有评论:
发表评论