File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Palindrome Partitioning Algorithm
3+ * Given a string, find all possible ways to partition it into palindromic substrings
4+ */
5+
6+ function isPalindrome ( s , left , right ) {
7+ while ( left < right ) {
8+ if ( s [ left ] !== s [ right ] ) return false ;
9+ left ++ ;
10+ right -- ;
11+ }
12+ return true ;
13+ }
14+
15+ function partition ( s ) {
16+ const result = [ ] ;
17+ const current = [ ] ;
18+
19+ function backtrack ( start ) {
20+ if ( start === s . length ) {
21+ result . push ( [ ...current ] ) ;
22+ return ;
23+ }
24+
25+ for ( let end = start ; end < s . length ; end ++ ) {
26+ if ( isPalindrome ( s , start , end ) ) {
27+ current . push ( s . substring ( start , end + 1 ) ) ;
28+ backtrack ( end + 1 ) ;
29+ current . pop ( ) ;
30+ }
31+ }
32+ }
33+
34+ backtrack ( 0 ) ;
35+ return result ;
36+ }
37+
38+ export { partition } ;
You can’t perform that action at this time.
0 commit comments