131. Palindrome Partitioning

代码1

DFS
Runtime: 3 ms, faster than 59.03% of Java online submissions for Palindrome Partitioning.

class Solution {
    public List<List<String>> partition(String s) {
        List<List<String>> res = new ArrayList();
        List<String> partition = new ArrayList();
        dfs(s, 0, res, partition);
        return res;
    }
    public void dfs(String s, int start, List<List<String>> res, List<String> partition) {
        if (start == s.length()) {
            res.add(new ArrayList(partition));
            return;
        }
        for (int i = start; i < s.length(); i++) {
            String substring = s.substring(start, i + 1);
            if (!isPalindrome(substring)) continue;
            partition.add(substring);
            dfs(s, i + 1, res, partition);
            partition.remove(partition.size() - 1);
        }
    }
    public boolean isPalindrome(String s) {
        int left = 0;
        int right = s.length() - 1;
        while (left < right) {
            if (s.charAt(left++) != s.charAt(right--)) return false;
        }
        return true;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。