Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1b66d86

Browse files
Trikcodeappgurueu
andauthored
Implemented Palindrome Partitioning using Backtracking algorithm (TheAlgorithms#1591)
* Implemented Palindrome Partitioning using Backtracking algorithm * fix:Updated palindromePartition algorithm * code clean up * Rephrase doc comment & move to appropriate function --------- Co-authored-by: Lars Müller <34514239+appgurueu@users.noreply.github.com>
1 parent 39d0113 commit 1b66d86

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

‎Recursive/PalindromePartitioning.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import { palindrome } from './Palindrome'
2+
3+
/*
4+
* Given a string s, return all possible palindrome partitionings of s.
5+
* A palindrome partitioning partitions a string into palindromic substrings.
6+
* @see https://www.cs.columbia.edu/~sedwards/classes/2021/4995-fall/proposals/Palindrome.pdf
7+
*/
8+
const partitionPalindrome = (s) => {
9+
const result = []
10+
backtrack(s, [], result)
11+
return result
12+
}
13+
14+
const backtrack = (s, path, result) => {
15+
if (s.length === 0) {
16+
result.push([...path])
17+
return
18+
}
19+
20+
for (let i = 0; i < s.length; i++) {
21+
const prefix = s.substring(0, i + 1)
22+
if (palindrome(prefix)) {
23+
path.push(prefix)
24+
backtrack(s.substring(i + 1), path, result)
25+
path.pop()
26+
}
27+
}
28+
}
29+
30+
export default partitionPalindrome
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import partitionPalindrome from '../PalindromePartitioning'
2+
3+
describe('Palindrome Partitioning', () => {
4+
it('should return all possible palindrome partitioning of s', () => {
5+
expect(partitionPalindrome('aab')).toEqual([
6+
['a', 'a', 'b'],
7+
['aa', 'b']
8+
])
9+
expect(partitionPalindrome('a')).toEqual([['a']])
10+
expect(partitionPalindrome('ab')).toEqual([['a', 'b']])
11+
})
12+
})

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /