Palindrome Partitioning
Cut a string into pieces so that every piece reads the same forwards and backwards.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
Try every prefix of what is left, starting from the shortest. If that prefix is a palindrome, cut it off, add it to the path, and solve the remaining suffix the same way. When nothing is left, the path is a complete partition.
Code
public static void Partition(string s, int start, List<string> path, List<List<string>> result) {
if (start == s.Length) { result.Add(new List<string>(path)); return; }
for (int end = start; end < s.Length; end++) {
string piece = s.Substring(start, end - start + 1);
if (!IsPalindrome(piece)) continue;
path.Add(piece);
Partition(s, end + 1, path, result);
path.RemoveAt(path.Count - 1);
}
}
static bool IsPalindrome(string s) {
int i = 0, j = s.Length - 1;
while (i < j) if (s[i++] != s[j--]) return false;
return true;
}static void partition(String s, int start, List<String> path, List<List<String>> result) {
if (start == s.length()) { result.add(new ArrayList<>(path)); return; }
for (int end = start; end < s.length(); end++) {
String piece = s.substring(start, end + 1);
if (!isPalindrome(piece)) continue;
path.add(piece);
partition(s, end + 1, path, result);
path.remove(path.size() - 1);
}
}
static boolean isPalindrome(String s) {
int i = 0, j = s.length() - 1;
while (i < j) if (s.charAt(i++) != s.charAt(j--)) return false;
return true;
}bool isPalindrome(const string& s) {
int i = 0, j = (int)s.size() - 1;
while (i < j) if (s[i++] != s[j--]) return false;
return true;
}
void partition(const string& s, int start, vector<string>& path, vector<vector<string>>& result) {
if (start == (int)s.size()) { result.push_back(path); return; }
for (int end = start; end < (int)s.size(); end++) {
string piece = s.substr(start, end - start + 1);
if (!isPalindrome(piece)) continue;
path.push_back(piece);
partition(s, end + 1, path, result);
path.pop_back();
}
}def partition(s: str, start: int, path: list[str], result: list[list[str]]) -> None:
if start == len(s): result.append(path[:]); return
for end in range(start, len(s)):
piece = s[start:end + 1]
if not is_palindrome(piece): continue
path.append(piece)
partition(s, end + 1, path, result)
path.pop()
def is_palindrome(s: str) -> bool:
return s == s[::-1]Tips
- The loop tries every cut length, not just the first palindrome found, because a short match can block a better partition later on.
- Checking IsPalindrome before recursing, instead of inside the base case, avoids building paths that could never work.
In the .NET library
Testing a substring for being a palindrome is O(n) by itself, so a naive version re-checks the same substrings many times. A real solution precomputes a table of which (start, end) ranges are palindromes.