8000 Implemented Palindrome Partitioning using Backtracking algorithm by Trikcode · Pull Request #1591 · TheAlgorithms/JavaScript · GitHub
[go: up one dir, main page]

Skip to content

Implemented Palindrome Partitioning using Backtracking algorithm #1591

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Nov 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions Recursive/PalindromePartitioning.js
Original file line number Diff line number Diff line change
@@ -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
12 changes: 12 additions & 0 deletions Recursive/test/PalindromePartitioning.test.js
Original file line number Diff line number Diff line change
@@ -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']])
})
})
0