给定一个字符串 s
,找到 s
中最长的回文子串。你可以假设 s
的最大长度为 1000。
示例 1:
输入: "babad" 输出: "bab" 注意: "aba" 也是一个有效答案。
示例 2:
输入: "cbbd" 输出: "bb"
public static string LongestPalindrome(string s) { string result = ""; if(string.IsNullOrWhiteSpace(s)) { return s; } if(s.Length == 1 || s.Length > 1000) { return s; } else if(s.Length == 2) { if(IsHuiZiChuan(s)) { return s; } else { return s[0].ToString(); } } List<string> listTmp = new List<string>(); int maxCount = 0; for(int i=0;i<s.Length -1;i++) { string si = s[i].ToString(); for (int j=i+1;j<s.Length;j++) { si += s[j]; if(IsHuiZiChuan(si)) { listTmp.Add(si); if(si.Length > maxCount) { maxCount = si.Length; result = si; } } else { continue; } } } if(result == "") { return s[0].ToString(); } return result; } public static bool IsHuiZiChuan(string str) { if(str.Length == 1) { return true; } for (int i = 0; i < (str.Length / 2); i++) { if(str[i] != str[str.Length - i -1]) { return false; } } return true; }
代码可以执行,但是时间和空间复杂度不佳,还需要进一步优化。