131. 分割回文串

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-partitioning
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


给了开始索引,从该索引开始截取,所有可能的字符串,只有回文字符串才可以进入到下一层


    Stack<String> stack = new Stack<>();
    List<List<String>> ret = new ArrayList<>();
    public List<List<String>> partition(String s) {

        dfs(s,0);
        return ret;

    }

    public void dfs(String s, int index) {
        // 如果到这步,说明之前可以拼接成回文串。
        if(s.length() == index) {
            ret.add(new ArrayList<>(stack));
            return;
        }
        // 开始位置截取字符串的所有可能
        for(int i=index;i<s.length();i++) {
            String str = s.substring(index,i+1);
            if(!isValid(str)) {
                continue;
            }
            stack.push(str);
            dfs(s,i+1);
            stack.pop();
        }
    }
    
    public boolean isValid(String str) {
        if(str.length() == 0) {
            return true;
        }

        int i=0;
        int j=str.length()-1;
        while(i < j) {
            if(str.charAt(i) != str.charAt(j)) {
                return false;
            }
            i++;
            j--;
        }
        return true;
    }
posted @ 2022-03-02 13:55  一颗青菜  阅读(4)  评论(0)    收藏  举报