Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public List<List<String>> partition(String s) {
- List<List<String>> result = new ArrayList<>();
- if (s == null) {
- return result;
- }
- if (s.length() == 0) {
- result.add(new ArrayList<String>());
- return result;
- }
- backtrack(result, new ArrayList<String>(), s, 0);
- return result;
- }
- public void backtrack(List<List<String>> list, ArrayList<String> tempList, String s, int start) {
- if (start == s.length()) {
- list.add(new ArrayList<String>(tempList));
- return;
- }
- for (int i = start; i < s.length(); i++) {
- if (isPalindrome(s, start, i)) {
- tempList.add(s.substring(start, i+1));
- backtrack(list, tempList, s, i + 1);
- tempList.remove(tempList.size() - 1);
- }
- }
- }
- public boolean isPalindrome (String s, int start, int end) {
- if (start == end) {
- return true;
- }
- while (start < end) {
- if (s.charAt(start++) != s.charAt(end--)) {
- return false;
- }
- }
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement