2016年7月21日星期四

[LeetCode] #131 Palindrome Partitioning

What's time complexity for this?

public class Solution {
    public List<List<String>> partition(String s) {
        List<List<String>> result = new ArrayList<>();
        if (s == null || s.length() == 0) {
            return result;
        }
        helper(result, new ArrayList<String>(), s, 0);
        return result;
    }
    
    private void helper(List<List<String>> result, List<String> path, String s, int start) {
        if (start >= s.length()) {
            result.add(new ArrayList<String>(path));
        }
        
        for (int i = start; i < s.length(); i++) {
            if (!isValid(s.substring(start, i + 1))) {
                continue;
            }
            path.add(s.substring(start, i + 1));
            helper(result, path, s, i + 1);
            path.remove(path.size() - 1);
        }
    }
    
    private boolean isValid(String s) {
        int start = 0;
        int end = s.length() - 1;
        while (start < end) {
            if (s.charAt(start) != s.charAt(end)) {
                return false;
            }
            start++;
            end--;
        }
        return true;
    }
}

没有评论:

发表评论