一、 问题描述
Leecode第五题,题目为:
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: “babad”
Output: “bab”
Note: “aba” is also a valid answer.
Example 2:
Input: “cbbd”
Output: “bb”
问题理解为:
最长回文子串
给定一个字符串s,找出s中的最长回文子串。假定字符串s的最大长度为1000字符。
例1:
输入:“babad”
输出: “bab”
注: "aba"也可以.
例 2:
输入: “cbbd”
输出: “bb”
二、解题思路
(1)回文字符串的概念:
字符串正序倒序相同
(2)分析:
对字符串中的字符依次遍历,具体做法为:以每个字符为中心,向左向右查找回文字符串。“aa”也是回文字符串,复杂度为:O(N^2)
三、实现代码
class Solution {
public String longestPalindrome(String s) {
if(s == null || s.length()==0)
return "";
int maxlength = 0;
String res = "";
for(int i=0;i<2*s.length()-1;i++)
{
int left = i/2;
int right = i/2;
if(i%2==1)
right++;
String str = Palindrome(s,left,right);
if(maxlength<str.length())
{
maxlength = str.length();
res = str;
}
}
return res;
}
private String Palindrome(String s, int left, int right)
{
while(left>=0 && right<s.length() && s.charAt(left)==s.charAt(right))
{
left--;
right++;
}
return s.substring(left+1,right);
}
}