https://github.com/emahtab/palindrome-partitioning
https://github.com/emahtab/palindrome-partitioning
backtracking leetcode palindrome-partitioning problem-solving
Last synced: 6 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/emahtab/palindrome-partitioning
- Owner: eMahtab
- Created: 2020-07-05T15:48:30.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2020-07-05T15:58:38.000Z (over 5 years ago)
- Last Synced: 2025-03-28T01:30:25.736Z (9 months ago)
- Topics: backtracking, leetcode, palindrome-partitioning, problem-solving
- Homepage:
- Size: 2.93 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Palindrome Partitioning
# https://leetcode.com/problems/palindrome-partitioning
# Implementation :
```java
class Solution {
public List> partition(String str) {
List> res = new ArrayList<>();
if (str.length() == 0) return res;
helper(res, new ArrayList(), str, 0);
return res;
}
private void helper(List> res, List current, String str, int start) {
// System.out.println("helper(res, current, str, " + start+")");
if (start == str.length()) {
// System.out.println(" Adding : " + current);
res.add(new ArrayList<>(current));
return;
}
int n = str.length();
for (int j = start; j < n; j++) {
if (isPalindrome(str, start, j)) {
// System.out.println("Palindrome : " + str.substring(start, j + 1));
current.add(str.substring(start, j + 1));
helper(res, current, str, j + 1);
current.remove(current.size() - 1);
}
}
}
private boolean isPalindrome(String str, int start, int end) {
while (start <= end) {
if (str.charAt(start++) != str.charAt(end--))
return false;
}
return true;
}
}
```
**Runtime Analysis :**
Time complexity: O(n*(2^n))
For a string with length n, there will be (n - 1) intervals between chars.
For every interval, we can cut it or not cut it, so there will be 2^(n - 1) ways to partition the string.
For every partition way, we need to check if it is palindrome, which is O(n).
So the time complexity is O(n*(2^n))
# References :
1. https://www.youtube.com/watch?v=A0wENqSIxK4
2. https://leetcode.com/problems/palindrome-partitioning/discuss/41963/Java:-Backtracking-solution./40308