Skip to content

Commit 63666f8

Browse files
committed
93. 复原 IP 地址
1 parent 05eae0f commit 63666f8

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@
4848
|82|[删除排序链表中的重复元素 II](https://leetcode.cn/problems/remove-duplicates-from-sorted-list-ii/)|[JavaScript](./algorithms/remove-duplicates-from-sorted-list-ii.js)|Medium|
4949
|83|[删除排序链表中的重复元素](https://leetcode.cn/problems/remove-duplicates-from-sorted-list/)|[JavaScript](./algorithms/remove-duplicates-from-sorted-list.js)|Easy|
5050
|88|[合并两个有序数组](https://leetcode.cn/problems/merge-sorted-array/)|[JavaScript](./algorithms/merge-sorted-array.js)|Easy|
51+
|93|[复原 IP 地址](https://leetcode.cn/problems/restore-ip-addresses/)|[JavaScript](./algorithms/restore-ip-addresses.js)|Medium|
5152
|94|[二叉树的中序遍历](https://leetcode.cn/problems/binary-tree-inorder-traversal/)|[JavaScript](./algorithms/binary-tree-inorder-traversal.js)|Easy|
5253
|98|[验证二叉搜索树](https://leetcode.cn/problems/validate-binary-search-tree/)|[JavaScript](./algorithms/validate-binary-search-tree.js)|Medium|
5354
|100|[相同的树](https://leetcode.cn/problems/same-tree/)|[JavaScript](./algorithms/same-tree.js)|Easy|

algorithms/restore-ip-addresses.js

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* 93. 复原 IP 地址
3+
* @param {string} s
4+
* @return {string[]}
5+
*/
6+
var restoreIpAddresses = function (s) {
7+
const result = [];
8+
const path = [];
9+
10+
const backtracking = (s, startIndex = 0) => {
11+
if (path.length === 4) {
12+
if (startIndex === s.length) {
13+
result.push(path.join("."));
14+
}
15+
return;
16+
}
17+
for (let i = startIndex; i < s.length; i++) {
18+
const str = s.slice(startIndex, i + 1);
19+
if (str.length >= 3 && str > 255) {
20+
break;
21+
}
22+
if (str.length > 1 && str[0] === "0") {
23+
// 排除前导0
24+
break;
25+
}
26+
path.push(str);
27+
backtracking(s, i + 1);
28+
path.pop();
29+
}
30+
};
31+
backtracking(s);
32+
33+
return result;
34+
};

0 commit comments

Comments
 (0)