64
64
65
65
<!-- 这里可写通用的实现逻辑 -->
66
66
67
- DFS。
67
+ ** 方法一:DFS**
68
+
69
+ 我们定义一个函数 $dfs(i)$,表示从字符串 $s$ 的第 $i$ 位开始,搜索能够组成的 IP 地址列表。
70
+
71
+ 函数 $dfs(i)$ 的执行步骤如下:
72
+
73
+ 如果 $i$ 大于等于字符串 $s$ 的长度,说明已经完成了四段 IP 地址的拼接,判断是否满足四段 IP 地址的要求,如果满足则将当前 $IP$ 加入答案。
74
+
75
+ 如果 $i$ 小于字符串 $s$ 的长度,此时还需要拼接 $IP$ 地址的一段,此时需要确定这一段 $IP$ 地址的值。如果该值大于 $255$,或者当前位置 $i$ 为 $0$ 且 $i$ 之后的若干位的数值大于 $0$,则说明不满足要求,直接返回。否则,将其加入 $IP$ 地址列表,并继续搜索下一段 $IP$ 地址。
76
+
77
+ 时间复杂度 $O(n \times 3^4)$,空间复杂度 $O(n)$。其中 $n$ 为字符串 $s$ 的长度。
68
78
69
79
<!-- tabs:start -->
70
80
75
85
``` python
76
86
class Solution :
77
87
def restoreIpAddresses (self , s : str ) -> List[str ]:
78
- def check (s ):
79
- if not (0 <= int (s) <= 255 ):
80
- return False
81
- if s[0 ] == ' 0' and len (s) > 1 :
88
+ def check (i : int , j : int ) -> int :
89
+ if s[i] == " 0" and i != j:
82
90
return False
83
- return True
91
+ return 0 <= int (s[i : j + 1 ]) <= 255
84
92
85
- def dfs (s , t ):
86
- if len (t) == 4 :
87
- if not s:
88
- ans.append(' .' .join(t))
93
+ def dfs (i : int ):
94
+ if i >= n and len (t) == 4 :
95
+ ans.append(" ." .join(t))
96
+ return
97
+ if i >= n or len (t) >= 4 :
89
98
return
90
- for i in range (1 , min (4 , len (s) + 1 )):
91
- if check(s[:i] ):
92
- t.append(s[:i ])
93
- dfs(s[i:], t )
99
+ for j in range (i , min (i + 3 , n )):
100
+ if check(i, j ):
101
+ t.append(s[i : j + 1 ])
102
+ dfs(j + 1 )
94
103
t.pop()
95
104
105
+ n = len (s)
96
106
ans = []
97
- dfs(s, [])
107
+ t = []
108
+ dfs(0 )
98
109
return ans
99
110
```
100
111
@@ -104,43 +115,36 @@ class Solution:
104
115
105
116
``` java
106
117
class Solution {
107
- private List<String > ans;
118
+ private int n;
119
+ private String s;
120
+ private List<String > ans = new ArrayList<> ();
121
+ private List<String > t = new ArrayList<> ();
108
122
109
123
public List<String > restoreIpAddresses (String s ) {
110
- ans = new ArrayList<> ();
111
- dfs(s, new ArrayList<> ());
124
+ n = s. length();
125
+ this . s = s;
126
+ dfs(0 );
112
127
return ans;
113
128
}
114
129
115
- private void dfs (String s , List<String > t ) {
116
- if (t. size() == 4 ) {
117
- if (" " . equals(s)) {
118
- ans. add(String . join(" ." , t));
119
- }
130
+ private void dfs (int i ) {
131
+ if (i >= n && t. size() == 4 ) {
132
+ ans. add(String . join(" ." , t));
120
133
return ;
121
134
}
122
- for (int i = 1 ; i < Math . min(4 , s. length() + 1 ); ++ i) {
123
- String c = s. substring(0 , i);
124
- if (check(c)) {
125
- t. add(c);
126
- dfs(s. substring(i), t);
127
- t. remove(t. size() - 1 );
128
- }
129
- }
130
- }
131
-
132
- private boolean check (String s ) {
133
- if (" " . equals(s)) {
134
- return false ;
135
- }
136
- int num = Integer . parseInt(s);
137
- if (num > 255 ) {
138
- return false ;
135
+ if (i >= n || t. size() >= 4 ) {
136
+ return ;
139
137
}
140
- if (s. charAt(0 ) == ' 0' && s. length() > 1 ) {
141
- return false ;
138
+ int x = 0 ;
139
+ for (int j = i; j < Math . min(i + 3 , n); ++ j) {
140
+ x = x * 10 + s. charAt(j) - ' 0' ;
141
+ if (x > 255 || (s. charAt(i) == ' 0' && i != j)) {
142
+ break ;
143
+ }
144
+ t. add(s. substring(i, j + 1 ));
145
+ dfs(j + 1 );
146
+ t. remove(t. size() - 1 );
142
147
}
143
- return true ;
144
148
}
145
149
}
146
150
```
@@ -151,75 +155,131 @@ class Solution {
151
155
class Solution {
152
156
public:
153
157
vector<string > restoreIpAddresses(string s) {
158
+ int n = s.size();
154
159
vector<string > ans;
155
160
vector<string > t;
156
- dfs(s, t, ans);
157
- return ans;
158
- }
159
-
160
- void dfs(string s, vector<string>& t, vector<string>& ans) {
161
- if (t.size() == 4) {
162
- if (s == "") {
163
- string p = "";
164
- for (auto e : t) p += e + ".";
165
- p.pop_back();
166
- ans.push_back(p);
161
+ function<void(int)> dfs = [ &] (int i) {
162
+ if (i >= n && t.size() == 4) {
163
+ ans.push_back(t[ 0] + "." + t[ 1] + "." + t[ 2] + "." + t[ 3] );
164
+ return;
167
165
}
168
- return ;
169
- }
170
- for (int i = 1 ; i < min(4 , (int ) s.size() + 1 ); ++i) {
171
- string c = s.substr(0, i);
172
- if (check(c)) {
173
- t.push_back(c);
174
- dfs (s.substr(i, s.size() - i), t, ans);
166
+ if (i >= n || t.size() >= 4) {
167
+ return;
168
+ }
169
+ int x = 0;
170
+ for (int j = i; j < min(n, i + 3); ++j) {
171
+ x = x * 10 + s[ j] - '0';
172
+ if (x > 255 || (j > i && s[ i] == '0')) {
173
+ break;
174
+ }
175
+ t.push_back(s.substr(i, j - i + 1));
176
+ dfs(j + 1);
175
177
t.pop_back();
176
178
}
177
- }
178
- }
179
-
180
- bool check(string s) {
181
- if (s == "") return false;
182
- int num = stoi(s);
183
- if (num > 255) return false;
184
- if (s[0] == '0' && s.size() > 1) return false;
185
- return true;
179
+ };
180
+ dfs(0);
181
+ return ans;
186
182
}
187
183
};
188
184
```
189
185
190
186
### **Go**
191
187
192
188
```go
193
- func restoreIpAddresses (s string ) []string {
194
- check := func (s string ) bool {
195
- if i , _ := strconv.Atoi (s); i > 255 {
196
- return false
197
- }
198
- if s[0 ] == ' 0' && len (s) > 1 {
199
- return false
189
+ func restoreIpAddresses(s string) (ans []string) {
190
+ n := len(s)
191
+ t := []string{}
192
+ var dfs func(int)
193
+ dfs = func(i int) {
194
+ if i >= n && len(t) == 4 {
195
+ ans = append(ans, strings.Join(t, "."))
196
+ return
200
197
}
201
- return true
202
- }
203
- var ans []string
204
- var dfs func (s string , t []string )
205
- dfs = func (s string , t []string ) {
206
- if len (t) == 4 {
207
- if s == " " {
208
- ans = append (ans, strings.Join (t, " ." ))
209
- }
198
+ if i >= n || len(t) == 4 {
210
199
return
211
200
}
212
- for i := 1 ; i < 4 && i < len (s)+ 1 ; i++ {
213
- if check (s[ 0 :i]) {
214
- t = append (t, s[ 0 :i] )
215
- dfs ( s[i:], t)
216
- t = t[ 0 : len (t)- 1 ]
201
+ x := 0
202
+ for j := i; j < i+3 && j < n; j++ {
203
+ x = x*10 + int(s[j]-'0' )
204
+ if x > 255 || (j > i && s[i] == '0') {
205
+ break
217
206
}
207
+ t = append(t, s[i:j+1])
208
+ dfs(j + 1)
209
+ t = t[:len(t)-1]
218
210
}
219
211
}
220
- var t []string
221
- dfs (s, t)
222
- return ans
212
+ dfs(0)
213
+ return
214
+ }
215
+ ```
216
+
217
+ ### ** TypeScript**
218
+
219
+ ``` ts
220
+ function restoreIpAddresses(s : string ): string [] {
221
+ const n = s .length ;
222
+ const ans: string [] = [];
223
+ const t: string [] = [];
224
+ const dfs = (i : number ): void => {
225
+ if (i >= n && t .length === 4 ) {
226
+ ans .push (t .join (' .' ));
227
+ return ;
228
+ }
229
+ if (i >= n || t .length === 4 ) {
230
+ return ;
231
+ }
232
+ let x = 0 ;
233
+ for (let j = i ; j < i + 3 && j < n ; ++ j ) {
234
+ x = x * 10 + s [j ].charCodeAt (0 ) - ' 0' .charCodeAt (0 );
235
+ if (x > 255 || (j > i && s [i ] === ' 0' )) {
236
+ break ;
237
+ }
238
+ t .push (x .toString ());
239
+ dfs (j + 1 );
240
+ t .pop ();
241
+ }
242
+ };
243
+ dfs (0 );
244
+ return ans ;
245
+ }
246
+ ```
247
+
248
+ ### ** C#**
249
+
250
+ ``` cs
251
+ public class Solution {
252
+ private IList <string > ans = new List <string >();
253
+ private IList <string > t = new List <string >();
254
+ private int n ;
255
+ private string s ;
256
+
257
+ public IList <string > RestoreIpAddresses (string s ) {
258
+ n = s .Length ;
259
+ this .s = s ;
260
+ dfs (0 );
261
+ return ans ;
262
+ }
263
+
264
+ private void dfs (int i ) {
265
+ if (i >= n && t .Count == 4 ) {
266
+ ans .Add (string .Join (" ." , t ));
267
+ return ;
268
+ }
269
+ if (i >= n || t .Count == 4 ) {
270
+ return ;
271
+ }
272
+ int x = 0 ;
273
+ for (int j = i ; j < i + 3 && j < n ; ++ j ) {
274
+ x = x * 10 + (s [j ] - '0' );
275
+ if (x > 255 || (j > i && s [i ] == '0' )) {
276
+ break ;
277
+ }
278
+ t .Add (x .ToString ());
279
+ dfs (j + 1 );
280
+ t .RemoveAt (t .Count - 1 );
281
+ }
282
+ }
223
283
}
224
284
```
225
285
0 commit comments