diff --git a/Recursive/PalindromePartitioning.js b/Recursive/PalindromePartitioning.js new file mode 100644 index 0000000000..9a5150f65d --- /dev/null +++ b/Recursive/PalindromePartitioning.js @@ -0,0 +1,30 @@ +import { palindrome } from './Palindrome' + +/* + * Given a string s, return all possible palindrome partitionings of s. + * A palindrome partitioning partitions a string into palindromic substrings. + * @see https://www.cs.columbia.edu/~sedwards/classes/2021/4995-fall/proposals/Palindrome.pdf + */ +const partitionPalindrome = (s) => { + const result = [] + backtrack(s, [], result) + return result +} + +const backtrack = (s, path, result) => { + if (s.length === 0) { + result.push([...path]) + return + } + + for (let i = 0; i < s.length; i++) { + const prefix = s.substring(0, i + 1) + if (palindrome(prefix)) { + path.push(prefix) + backtrack(s.substring(i + 1), path, result) + path.pop() + } + } +} + +export default partitionPalindrome diff --git a/Recursive/test/PalindromePartitioning.test.js b/Recursive/test/PalindromePartitioning.test.js new file mode 100644 index 0000000000..1bb218cdd4 --- /dev/null +++ b/Recursive/test/PalindromePartitioning.test.js @@ -0,0 +1,12 @@ +import partitionPalindrome from '../PalindromePartitioning' + +describe('Palindrome Partitioning', () => { + it('should return all possible palindrome partitioning of s', () => { + expect(partitionPalindrome('aab')).toEqual([ + ['a', 'a', 'b'], + ['aa', 'b'] + ]) + expect(partitionPalindrome('a')).toEqual([['a']]) + expect(partitionPalindrome('ab')).toEqual([['a', 'b']]) + }) +})
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies: