File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @param {string } s
3+ * @return {string[] }
4+ */
5+ let restoreIpAddresses = function ( s ) {
6+ let res = [ ]
7+ let findPos = ( start , prev , used ) => {
8+ if ( used === 3 ) {
9+ // 点全部用光后 剩余字符的长度不能超过3 就是一个答案
10+ let rest = s . substr ( start )
11+ // 最后一位不能为0 且长度在 (0,3] 范围内
12+ if ( isValidChunk ( rest ) ) {
13+ res . push ( prev . concat ( rest ) . join ( "." ) )
14+ }
15+ return
16+ }
17+
18+ for ( let i = 1 ; i <= 3 ; i ++ ) {
19+ let end = start + i
20+ let cur = s . substring ( start , end )
21+ if ( isValidChunk ( cur ) ) {
22+ findPos ( end , prev . concat ( cur ) , used + 1 )
23+ }
24+ }
25+ }
26+
27+ findPos ( 0 , [ ] , 0 )
28+
29+ return res
30+ }
31+
32+ function isValidChunk ( str ) {
33+ let strLen = str . length
34+ if ( strLen === 0 ) {
35+ return false
36+ }
37+ // 开头是0的话 只能整个字符串只有一位0才行
38+ if ( str [ 0 ] === "0" ) {
39+ return strLen === 1
40+ }
41+ let num = Number ( str )
42+ return num <= 255
43+ }
You can’t perform that action at this time.
0 commit comments