[刷题]Palindrome Partitioning

原创 2015年07月08日 20:20:28

[刷题]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;
    }
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

136.Palindrome Partitioning-分割回文串(中等题)

分割回文串 题目给定一个字符串s,将s分割成一些子串,使每个子串都是回文串。 返回s所有可能的回文串分割方案。 样例 给出 s = “aab”,返回 题解回溯法,如s = “aab”,对s进行遍历...

[leetcode]Palindrome Partitioning II

Palindrome Partitioning II   Given a string s, partition s such that every substring of the ...

1044 - Palindrome Partitioning (记忆化搜索乱搞)

1044 - Palindrome Partitioning PDF (English) Statistics Forum ...

LeetCode | Palindrome Partitioning II(最少切割次数将一个子串划分成回文子串)

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

LeetCode OJ:Palindrome Partitioning II

Palindrome Partitioning II  Total Accepted: 3866 Total Submissions: 22882My Submissions Given a...

[LeetCode] Palindrome Partitioning II

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

LeetCode 131. Palindrome Partitioning 树形问题,状态回溯

131. Palindrome Partitioning Given a string s, partition s such that every substring of the partit...

LeetCode 之 Palindrome Partitioning II(动态规划)

LeetCode 之 Palindrome Partitioning II,本文给出基于动态规划算法思想与状态转换表达式,最后,贴上C++详细源码实现。.

Palindrome Partitioning

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

[LeetCode]132. Palindrome Partitioning II

[LeetCode]132. Palindrome Partitioning II题目描述思路动态规划 开始考虑,和单词划分很像 但是简单的遍历加计算是否回文串总共需要n^3的时间复杂度 优化:...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)