Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Solution {
- /**
- * @param s: A string
- * @return: A list of lists of string
- */
- public List<List<String>> partition(String s) {
- // write your code here
- List<List<String>> result = new ArrayList<>();
- if (s == null || s.isEmpty()) {
- return result;
- }
- List<String> palindrome = new ArrayList<>();
- partitionHelper(s, 0, result, palindrome);
- return result;
- }
- public void partitionHelper(String s, int pos, List<List<String>> result, List<String> palindrome){
- if (s.length() == pos) {
- result.add(new ArrayList<String>(palindrome));
- return;
- }
- for (int i = pos + 1; i <= s.length(); i++) {
- String temp = s.substring(pos, i);
- if (!isPalindrome(temp)) {
- continue;
- }
- palindrome.add(temp);
- partitionHelper(s, i, result, palindrome);
- palindrome.remove(palindrome.size() - 1);
- }
- }
- public boolean isPalindrome(String words) {
- if (words == null || words.isEmpty()) {
- return false;
- }
- int length = words.length();
- for (int i = 0; i < length - i; i++) {
- if (words.charAt(i) != words.charAt(length - i - 1)) {
- return false;
- }
- }
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement