5. Longest Palindromic Substring

 
  
/**
 * Created by zhangwd4 on 2017/12/25.
 *
 * 题目意思是:找出一个字符串的最大回文子字符串。意思就是中心对称的子字符串。当
 * 然分两种情况
 * 1 奇数类型的对称 如 aba
 * 2 偶数类型的对称 如 abba
 *
 */
public class LeetCode5 {

    int start = 0;
    int end = 0;

    public String longestPalindrome(String s) {
        if (null == s || s.isEmpty() || s.length() == 1)
            return s;

        for (int i = 0; i < s.length() - 1; i++) {
            findPalindrome(s, i, i); //aba形式的
            findPalindrome(s, i, i + 1);//abba形式的
        }
        return s.substring(start, end);
    }

    private void findPalindrome(String s, int from, int to) {
        while (from >= 0 && to < s.length() && (s.charAt(from) == s.charAt(to))) {
            from--;
            to++;
        }
        if (end - start < to - from) {
            start = from + 1;
            end = to;
        }

    }

    public static void main(String args[]) {
        String s = "a";

        String result = new LeetCode5().longestPalindrome(s);

        System.out.println(result);
    }
}

你可能感兴趣的:(java,leetcode,算法,string,substring,ACM算法)