美文网首页
5. Longest Palindromic Substring

5. Longest Palindromic Substring

作者: lixwcqs | 来源:发表于2018-03-16 22:58 被阅读0次

    Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

    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"
    
    public String longestPalindrome(String s) {
            if (s == null || s.length() <= 1) return s;
            final char[] chars = s.toCharArray();
            int len = 1;//回数长度
            int left = 0;
            int right = 0;
            for (int i = 0; i < chars.length; ++i) {
                for (int j = chars.length - 1; j > i; --j) {
                    if ((j - i + 1) > len) {
                        if (isPalindrome(chars, i, j)) {
                            len = j - i + 1;
                            left = i;
                            right = j;
                        }
                    } else {
                        break;
                    }
                }
            }
            return s.substring(left, right + 1);
        }
    
      //判断是否是回数
       private boolean isPalindrome(char[] chars, int left, int right) {
            int i = left;
            int j = right;
            while (i < j) {
                if (chars[i++] != chars[j--]) {
                    return false;
                }
            }
            return true;
        }
    

    相关文章

      网友评论

          本文标题:5. Longest Palindromic Substring

          本文链接:https://www.haomeiwen.com/subject/zccdqftx.html