Palindrome Partitioning leetcode

lpy1990

Palindrome Partitioning

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"]   ]

回溯法

说明

用对于每个子集检测是否是回文串, 如果是就从下一个指针来继续搜索.

复杂度

时间O(2^n)

代码

public List<List<String>> partition(String s) {
    List<List<String>> res = new ArrayList<List<String>>();
    if (s == null || s.length() == 0) {
        return res;
    }
    List<String> tem = new ArrayList<String>();
    helper(s, res, tem, 0);
    return res;
}
public void helper(String s, List<List<String>> res, List<String> tem, int pos) {
    if (pos == s.length()) {
        res.add(new ArrayList<String>(tem));
        return;
    }
    for (int i = pos; i < s.length(); i++) {
        if (isValid(s.substring(pos, i + 1))) {
            tem.add(s.substring(pos, i + 1));
            helper(s, res, tem, i + 1);
            tem.remove(tem.size() - 1);
        }
    }
}
public boolean isValid(String s) {
    int left = 0; 
    int right = s.length() - 1;
    while (left < right) {
        if (s.charAt(left) != s.charAt(right)) {
            return false;
        }
        left++;
        right--;
    }
    return true;
}
阅读 1.7k

26 声望
10 粉丝
0 条评论
26 声望
10 粉丝
文章目录
宣传栏