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”
思路在于遍历找到各个可以作为中点的单个字母或两个相同的字母,然后利用ExpendCenter方法来获取最长的结果并和最终结果比较,取最长。
public class Solution {
public string LongestPalindrome(string s) {
if(s.Length <= 1) return s;
string res = s.Substring(0,1);
for (int i = 0; i < s.Length; i++ ){
string temp1 = ExpendCenter(s,i,i);
string temp2 = ExpendCenter(s,i,i+1);
if(res.Length<temp1.Length) res = temp1;
if(res.Length<temp2.Length) res = temp2;
}
return res;
}
public static string ExpendCenter(string s, int l,int r)
{
while(l>=0 && r<s.Length && s[l]==s[r])
{
l--;
r++;
}
return s.Substring(l+1,r-l-1);
}
}