leetcode 5. Longest Palindromic Substring

来源:互联网 发布:北京博奥网络教育 编辑:程序博客网 时间:2024/05/12 06:41

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

找到一个字符串中的最长连续回文串.

以一个字符或两个字符为中心,向两边扩展找回文串.

public class A05LongestPalindromicSubstring_1 {    public String longestPalindrome(String s) {    int begin = 0, end = 1;    int len1, len2, len;        for(int i = 0; i < s.length(); i++) {        len1 = findPalindrome(s, i, i);        len2 = findPalindrome(s, i, i + 1);        len = Math.max(len1, len2);        if(len > end - begin) {        begin = i - (len - 1) / 2;        end = i + 1 + len / 2;        }        }        return s.substring(begin, end);    }        public int findPalindrome(String s, int left, int right) {    while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {    left--;    right++;    }    return right - left - 1;    }}


1 0
原创粉丝点击