g0101_0200.s0131_palindrome_partitioning.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java Show documentation
Show all versions of leetcode-in-java Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
The newest version!
package g0101_0200.s0131_palindrome_partitioning;
// #Medium #Top_100_Liked_Questions #Top_Interview_Questions #String #Dynamic_Programming
// #Backtracking #Big_O_Time_O(N*2^N)_Space_O(2^N*N)
// #2024_11_13_Time_7_ms_(98.55%)_Space_56.9_MB_(57.45%)
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings("java:S5413")
public class Solution {
public List> partition(String s) {
List> res = new ArrayList<>();
backtracking(res, new ArrayList<>(), s, 0);
return res;
}
private void backtracking(List> res, List currArr, String s, int start) {
if (start == s.length()) {
res.add(new ArrayList<>(currArr));
}
for (int end = start; end < s.length(); end++) {
if (!isPanlindrome(s, start, end)) {
continue;
}
currArr.add(s.substring(start, end + 1));
backtracking(res, currArr, s, end + 1);
currArr.remove(currArr.size() - 1);
}
}
private boolean isPanlindrome(String s, int start, int end) {
while (start < end && s.charAt(start) == s.charAt(end)) {
start++;
end--;
}
return start >= end;
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy