[刷题]Palindrome Partitioning

来源:互联网 发布:js判断是否为质数 编辑:程序博客网 时间:2024/06/07 07:07

[刷题]Palindrome Partitioning

public class Solution {    /**     * @param s: A string     * @return: A list of lists of string     */    public List<List<String>> partition(String s) {        // 2015-07-08        List<List<String>> rst = new ArrayList<List<String>>();        if (s == null || s.length() == 0) {            return rst;        }        ArrayList<String> list = new ArrayList<>();                helper(rst, list, s, 0);        return rst;    }        // 注意第一个参数的类型    private void helper(List<List<String>> rst, ArrayList<String> list, String s, int pos) {        if (pos == s.length()) {            rst.add(new ArrayList<String>(list));            return;        }                for (int i = pos + 1; i <= s.length(); i++) { //注意是<=            if (!isPalindrome(s.substring(pos, i))) {                continue;            }            list.add(s.substring(pos, i));            helper(rst, list, s, i);            list.remove(list.size() - 1);        }        return;    }        private boolean isPalindrome(String s) {        if (s.length() == 0) {            return true;        }        int start = 0;        int end = s.length() - 1;        while (start < end) {            if (s.charAt(start) != s.charAt(end)) {                return false;            }            start++;            end--;        }        return true;    }}


0 0
原创粉丝点击