Palindrome partitioning

沒有很難,將字串拆分成小字串再去檢查是不是回文即可

public List<List<String>> partition(String s) {
    // write your code here
    List<List<String>> results = new ArrayList<>();
    if (s == null || s.length() == 0 ) {
        return results;
    }

    helper(s, 0, new ArrayList<String>(), results);
    return results;
}

boolean isPalindrome(String str) {
    int len = str.length();

    for (int i = 0; i < len / 2; i++) {
        if (str.charAt(i) != str.charAt(len - i - 1)) {
            return false;
        }
    }
    return true;
}

public void helper(String s, 
                    int startIndex, 
                    List<String> palindromes,
                    List<List<String>> results) {
    if (startIndex == s.length()) {
        results.add(new ArrayList<String>(palindromes));
        return;
    }

    for (int i = startIndex; i < s.length(); i++) {
        //no need double loop, recursion will do that
        String tmp = s.substring(startIndex, i + 1);
        if (!isPalindrome(tmp)) {
            continue;
        }
        palindromes.add(tmp);
        helper(s, i+1, palindromes, results);
        palindromes.remove(palindromes.size() - 1);
    }
    return;
}

results matching ""

    No results matching ""