@@ -450,6 +450,101 @@ var partition = function(s) {
450
450
};
451
451
```
452
452
453
+ ##C
454
+ ``` c
455
+ char ** path;
456
+ int pathTop;
457
+ char *** ans;
458
+ int ansTop = 0 ;
459
+ int * ansSize;
460
+
461
+ // 将path中的字符串全部复制到ans中
462
+ void copy () {
463
+ //创建一个临时tempPath保存path中的字符串
464
+ char** tempPath = (char**)malloc(sizeof(char*) * pathTop);
465
+ int i;
466
+ for(i = 0; i < pathTop; i++) {
467
+ tempPath[i] = path[i];
468
+ }
469
+ //保存tempPath
470
+ ans[ansTop] = tempPath;
471
+ //将当前path的长度(pathTop)保存在ansSize中
472
+ ansSize[ansTop++] = pathTop;
473
+ }
474
+
475
+ // 判断字符串是否为回文字符串
476
+ bool isPalindrome (char* str, int startIndex, int endIndex) {
477
+ //双指针法:当endIndex(右指针)的值比startIndex(左指针)大时进行遍历
478
+ while(endIndex >= startIndex) {
479
+ //若左指针和右指针指向元素不一样,返回False
480
+ if(str[ endIndex--] != str[ startIndex++] )
481
+ return 0;
482
+ }
483
+ return 1;
484
+ }
485
+
486
+ //切割从startIndex到endIndex子字符串
487
+ char* cutString(char* str, int startIndex, int endIndex) {
488
+ //开辟字符串的空间
489
+ char* tempString = (char* )malloc(sizeof(char) * (endIndex - startIndex + 2));
490
+ int i;
491
+ int index = 0;
492
+ //复制子字符串
493
+ for(i = startIndex; i <= endIndex; i++)
494
+ tempString[ index++] = str[ i] ;
495
+ //用'\0'作为字符串结尾
496
+ tempString[ index] = '\0';
497
+ return tempString;
498
+ }
499
+
500
+ void backTracking(char* str, int strLen, int startIndex) {
501
+ if(startIndex >= strLen) {
502
+ //将path拷贝到ans中
503
+ copy();
504
+ return ;
505
+ }
506
+
507
+ int i;
508
+ for(i = startIndex; i < strLen; i++) {
509
+ //若从subString到i的子串是回文字符串,将其放入path中
510
+ if(isPalindrome(str, startIndex, i)) {
511
+ path[pathTop++] = cutString(str, startIndex, i);
512
+ }
513
+ //若从startIndex到i的子串不为回文字符串,跳过这一层
514
+ else {
515
+ continue;
516
+ }
517
+ //递归判断下一层
518
+ backTracking(str, strLen, i + 1);
519
+ //回溯,将path中最后一位元素弹出
520
+ pathTop--;
521
+ }
522
+ }
523
+
524
+ char*** partition(char* s, int* returnSize, int** returnColumnSizes){
525
+ int strLen = strlen(s);
526
+ //因为path中的字符串最多为strLen个(即单个字符的回文字符串),所以开辟strLen个char* 空间
527
+ path = (char** )malloc(sizeof(char* ) * strLen);
528
+ //存放path中的数组结果
529
+ ans = (char*** )malloc(sizeof(char** ) * 40000);
530
+ //存放ans数组中每一个char** 数组的长度
531
+ ansSize = (int* )malloc(sizeof(int) * 40000);
532
+ ansTop = pathTop = 0;
533
+
534
+ //回溯函数
535
+ backTracking(s, strLen, 0);
536
+
537
+ //将ansTop设置为ans数组的长度
538
+ *returnSize = ansTop;
539
+ //设置ans数组中每一个数组的长度
540
+ *returnColumnSizes = (int*)malloc(sizeof(int) * ansTop);
541
+ int i;
542
+ for(i = 0; i < ansTop; ++i) {
543
+ (*returnColumnSizes)[i] = ansSize[i];
544
+ }
545
+ return ans;
546
+ }
547
+ ```
453
548
454
549
-----------------------
455
550
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
0 commit comments