leetcode 647获取字符串的回文子串

leetcode 647


问题描述:

获取一个字符串的回文子串list和其回文子串数量

输入:

字符串s

输出:

该字符串的回文子串列表。

思路:

1.在子串中使用由中间向两边扩展的方式判断一个字符串是否是回文字符串。

    public List<String> extendRoundCenter(String s, int start, int end) {
        List<String> res = new LinkedList<>();
        while (start >= 0 && end < s.length() && s.charAt(start) == s.charAt(end)) {
            res.add(s.substring(start,end+1));
            start --;
            end ++;
        }
        return res;
    }

重点: 每次向两边扩展的时候就说明已经是一个回文子串了,使用一个list列表来存储回文子串,最后返回给调用他的函数进行汇总。

2.在循环的时候,使用一个list表来存储每次获取的结果列表,并且在判断字符串某一部分是不是回文串的时候要注意分奇数和偶数,奇数由自身开始扩展,偶数由自身和自身后两个字符开始扩展。

    public List<String> countSubstrings(String s) {
        List<String> res= new LinkedList<>();
        if (s == null || s.length() == 0) {
            return res;
        }
        int length = s.length();
        for (int i = 0; i < length; i++) {
            res.addAll(extendRoundCenter(s, i, i));
            res.addAll(extendRoundCenter(s, i, i+1));
        }
        System.out.println(res);
        System.out.println(res.size());
        return res;
    }

重点: 注意在调用子串是否是回文串的时候参数(i,i)和(i,i+1)前者是奇数,以自身为中心(这时候即使只有一个单独的字符也会被算作回文串),后者是偶数,是以连续两个字符为中心扩展。最后将结果列表返回就是想得到的回文子列表。

代码:

public class lee647 {
    public static void main(String[] args) {
        lee647 lee647 = new lee647();
        lee647.countSubstrings("abcc");
    }

    public List<String> countSubstrings(String s) {
        List<String> res= new LinkedList<>();
        if (s == null || s.length() == 0) {
            return res;
        }
        int length = s.length();
        for (int i = 0; i < length; i++) {
            res.addAll(extendRoundCenter(s, i, i));
            res.addAll(extendRoundCenter(s, i, i+1));
        }
        System.out.println(res);
        System.out.println(res.size());
        return res;
    }

    public List<String> extendRoundCenter(String s, int start, int end) {
        List<String> res = new LinkedList<>();
        while (start >= 0 && end < s.length() && s.charAt(start) == s.charAt(end)) {
            res.add(s.substring(start,end+1));
            start --;
            end ++;
        }
        return res;
    }
}

image

超过96.55%的提交

张双江

2018年4月21日15:30:04

猜你喜欢

转载自blog.csdn.net/zsjwish/article/details/80030289