1- // Leetcode 131
2- // Language: Javascript
3- // Problem: https://leetcode.com/problems/palindrome-partitioning/
4- // Author: Chihung Yu
51/**
62 * @param {string } s
7- * @returns {string[][] }
3+ * @return {string[][] }
84 */
95var partition = function ( s ) {
10-
116 var result = [ ] ;
12- var list = [ ] ;
137
14- if ( s === null || s . length === 0 ) {
15- return [ ] ;
16- }
8+ generate ( s , 0 , [ ] , result ) ;
179
18- calculate ( s , result , list ) ;
1910 return result ;
2011} ;
2112
22- var isPalindrome = function ( s ) {
23- var i = 0 ;
24- var j = s . length - 1 ;
13+ var generate = function ( s , index , output , result ) {
14+ if ( index === s . length ) {
15+ result . push ( output . slice ( ) ) ;
16+ return ;
17+ }
2518
26- while ( i < j ) {
27- if ( s [ i ] !== s [ j ] ) {
28- return false ;
29- }
19+
20+ for ( var i = index ; i < s . length ; i ++ ) {
21+ var str = s . substring ( index , i ) ;
3022
31- i ++ ;
32- j -- ;
23+ if ( isPalindrome ( s , index , i ) ) {
24+ output . push ( s . substring ( index , i + 1 ) ) ;
25+ generate ( s , i + 1 , output , result ) ;
26+ output . pop ( ) ;
27+ }
3328 }
34-
35- return true ;
3629}
3730
38- var calculate = function ( s , result , list ) {
39- if ( s . length === 0 ) {
40- result . push ( list . slice ( ) ) ;
41- return ;
42- }
43-
44- for ( var i = 1 ; i <= s . length ; i ++ ) {
45- var substring = s . substring ( 0 , i ) ;
46-
47- if ( isPalindrome ( substring ) ) {
48- list . push ( substring ) ;
49- var restSubstring = s . substring ( i ) ;
50-
51- calculate ( restSubstring , result , list ) ;
52- list . pop ( ) ;
31+ var isPalindrome = function ( s , head , tail ) {
32+ while ( head < tail ) {
33+ if ( s [ head ] !== s [ tail ] ) {
34+ return false ;
5335 }
36+
37+ head ++ ;
38+ tail -- ;
5439 }
40+
41+ return true ;
5542}
0 commit comments