LeetCode 5 Longest Palindromic Substring

题目:Given a stringS, find the longest palindromic substring inS. You may assume that the maximum length ofSis 1000, and there exists one unique longest palindromic substring.

翻译:求字符串的最长回文子串

思路:既然是求最长回文串,那么就找到每一个回文串,然后把最长的长度标记处理就好。
但是回文串会有奇数位和偶数位,所以要分情况去求最大长度。
即通过对每一个字符求最长的奇数和偶数回文串,并记录开始位置和最大长度。最后遍历结束,返回字串OK了。
	public String longestPalindrome(String s) {
        int len = s.length();
        if(len <= 1)
        	return s;
        int start = 0, maxlen = 0;
        for(int i = 1;i <len;i++)
        {
        	int low = i-1;
        	int high = i;
        	while(low>=0&& high<len &&s.charAt(low)==s.charAt(high))
        	{
        		low--;
        		high++;
        	}
        	if(high-low -2+1>maxlen)
        	{
        		maxlen = high-low-1;
        		start = low + 1;
        	}
        	
        	low = i -1;
        	high = i+1;
        	while(low>=0&&high<len&&s.charAt(low)==s.charAt(high))
        	{
        		low--;
        		high++;
        	}
        	if(high -low -1>maxlen)
        	{
        		maxlen = high - low -1;
        		start = low +1;
        	}
        	
        }
		return s.substring(start,start+maxlen);
    }

high - low -2 +1 是因为上一步结束时 low 和high分别向左右扩展了1 ,此时应该减去 2,但是求长度又需加1。
PS: 自以为Java也有C++的substr ,试了几次,才发现并没有。。

你可能感兴趣的:(substring)