美文网首页Leetcode每日两题程序员
Leetcode 131. Palindrome Partiti

Leetcode 131. Palindrome Partiti

作者: ShutLove | 来源:发表于2017-10-20 19:07 被阅读8次

    Given a string s, partition s such that every substring of the partition is a palindrome.
    Return all possible palindrome partitioning of s.

    For example, given s = "aab",
    Return
    [
    ["aa","b"],
    ["a","a","b"]
    ]

    题意:找出一个字符串所有可能的回文子串组合。

    思路:深度搜索所有组合,每找出一个子串,就判断一下是否是回文串,找到最后一个位置,那么就是一个符合条件的组合。

    public List<List<String>> partition(String s) {
        List<List<String>> res = new ArrayList<>();
        if (s == null || s.length() == 0) {
            return res;
        }
    
        HashMap<String, Boolean> memory = new HashMap<>();
        dfsPalindrome(s, 0, new ArrayList<>(), res, memory);
    
        return res;
    }
    
    private void dfsPalindrome(String s, int start, List<String> subres, List<List<String>> res, HashMap<String, Boolean> memory) {
        if (start == s.length()) {
            res.add(new ArrayList<>(subres));
            return;
        }
    
        for (int end = start + 1; end <= s.length(); end++) {
            String tmp = s.substring(start, end);
            if (!isPalindrome(tmp, memory)) {
                continue;
            }
            subres.add(tmp);
            dfsPalindrome(s, end, subres, res, memory);
            subres.remove(subres.size() - 1);
        }
    }
    
    private boolean isPalindrome(String tmp, HashMap<String, Boolean> memory) {
        if (memory.containsKey(tmp)) {
            return true;
        }
        int start = 0, end = tmp.length() - 1;
        while (start < end) {
            if (tmp.charAt(start) != tmp.charAt(end)) {
                return false;
            }
            start++;
            end--;
        }
        memory.put(tmp, true);
    
        return true;
    }

    相关文章

      网友评论

        本文标题:Leetcode 131. Palindrome Partiti

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