Given a string, find the length of the longest substring without repeating characters.
Examples:
Given “abcabcbb”, the answer is “abc”, which the length is 3.
Given “bbbbb”, the answer is “b”, with the length of 1.
Given “pwwkew”, the answer is “wke”, with the length of 3. Note that the answer must be a substring, “pwke” is a subsequence and not a substring.
解:我的思路是针对奇数回文和偶数回文的情况分别进行判定,对每一个元素遍历求出以其为中心的回文的最大长度。时间复杂度o(n*n)。网上还有一种Manacher’s Algorithm 据说可以实现线性时间复杂度,我只看了它的思想,并未实现代码。可参考:
http://articles.leetcode.com/longest-palindromic-substring-part-ii
public String longestPalindrome(String s) {
if (s == null || s.length() == 1 || s == "") return s;
String result = null;
int length = 0;
//奇数回文的情况
for (int i = 1;i<s.length() - 1;i++){
int j =1;
while (i + j < s.length() && i - j >= 0){
if (s.charAt(i+j) != s.charAt(i-j)){
if (j * 2 - 1 > length){
length = j*2-1;
result = s.substring(i - j + 1, i + j);
}
break;
}else {
//到达边界仍然满足条件
if (i + j == s.length() - 1 || i - j == 0){
if (j * 2 + 1 > length){
length = j*2+1;
result = s.substring(i-j,i+j+1);
break;
}
}
j++;
}
}
}
//偶数回文的情况
for (int i = 0;i<s.length() - 1;i++){
int j =1;
while (i + j < s.length() && i+1-j >= 0){
if (s.charAt(i+j) != s.charAt(i+1-j)){
if (j * 2 - 2 > length){
length = j*2-2;
result = s.substring(i - j + 2, i + j);
}
break;
}else {
if (i + j == s.length() - 1 || i+1-j == 0){
if (j * 2 > length){
length = j*2;
result = s.substring(i-j+1,i+j+1);
break;
}
}
j++;
}
}
}
return result;
}