Skip to content

Commit 05eae0f

Browse files
committed
131. 分割回文串
1 parent 99a9810 commit 05eae0f

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@
7272
|124|[二叉树中的最大路径和](https://leetcode.cn/problems/binary-tree-maximum-path-sum/)|[JavaScript](./algorithms/binary-tree-maximum-path-sum.js)|Hard|
7373
|125|[验证回文串](https://leetcode.cn/problems/valid-palindrome/)|[JavaScript](./algorithms/valid-palindrome.js)|Easy|
7474
|129|[求根节点到叶节点数字之和](https://leetcode.cn/problems/sum-root-to-leaf-numbers/)|[JavaScript](./algorithms/sum-root-to-leaf-numbers.js)|Medium|
75+
|131|[分割回文串](https://leetcode.cn/problems/palindrome-partitioning/)|[JavaScript](./algorithms/palindrome-partitioning.js)|Medium|
7576
|136|[只出现一次的数字](https://leetcode-cn.com/problems/single-number/)|[JavaScript](./algorithms/single-number.js)|Easy|
7677
|141|[环形链表](https://leetcode-cn.com/problems/linked-list-cycle/)|[JavaScript](./algorithms/linked-list-cycle.js)|Easy|
7778
|142|[环形链表 II](https://leetcode.cn/problems/linked-list-cycle-ii/)|[JavaScript](./algorithms/linked-list-cycle-ii.js)|Medium|

algorithms/palindrome-partitioning.js

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* 131. 分割回文串
3+
* @param {string} s
4+
* @return {string[][]}
5+
*/
6+
var partition = function (s) {
7+
const result = [];
8+
const path = [];
9+
10+
const backtracking = (s, startIndex = 0) => {
11+
if (startIndex >= s.length) {
12+
result.push(path.slice());
13+
return;
14+
}
15+
for (let i = startIndex; i < s.length; i++) {
16+
if (isPalindrome(s, startIndex, i)) {
17+
const str = s.slice(startIndex, i + 1);
18+
path.push(str);
19+
} else {
20+
continue;
21+
}
22+
backtracking(s, i + 1);
23+
path.pop();
24+
}
25+
};
26+
backtracking(s);
27+
28+
return result;
29+
};
30+
31+
function isPalindrome(s, left, right) {
32+
while (left < right) {
33+
if (s[left] !== s[right]) {
34+
return false;
35+
}
36+
left++;
37+
right--;
38+
}
39+
return true;
40+
}

0 commit comments

Comments
 (0)