Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 61d479e

Browse files
improving java solution by using stringBuilder
1. improving java solution by using stringBuilder 2. adding explanation in the code
1 parent a039519 commit 61d479e

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

‎problems/0093.复原IP地址.md‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,47 @@ class Solution {
314314
return true;
315315
}
316316
}
317+
//方法一:但使用stringBuilder,故优化时间、空间复杂度,因为向字符串插入字符时无需复制整个字符串,从而减少了操作的时间复杂度,也不用开新空间存subString,从而减少了空间复杂度。
318+
class Solution {
319+
List<String> result = new ArrayList<>();
320+
public List<String> restoreIpAddresses(String s) {
321+
StringBuilder sb = new StringBuilder(s);
322+
backTracking(sb, 0, 0);
323+
return result;
324+
}
325+
private void backTracking(StringBuilder s, int startIndex, int dotCount){
326+
if(dotCount == 3){
327+
if(isValid(s, startIndex, s.length() - 1)){
328+
result.add(s.toString());
329+
}
330+
return;
331+
}
332+
for(int i = startIndex; i < s.length(); i++){
333+
if(isValid(s, startIndex, i)){
334+
s.insert(i + 1, '.');
335+
backTracking(s, i + 2, dotCount + 1);
336+
s.deleteCharAt(i + 1);
337+
}else{
338+
break;
339+
}
340+
}
341+
}
342+
//[start, end]
343+
private boolean isValid(StringBuilder s, int start, int end){
344+
if(start > end)
345+
return false;
346+
if(s.charAt(start) == '0' && start != end)
347+
return false;
348+
int num = 0;
349+
for(int i = start; i <= end; i++){
350+
int digit = s.charAt(i) - '0';
351+
num = num * 10 + digit;
352+
if(num > 255)
353+
return false;
354+
}
355+
return true;
356+
}
357+
}
317358

318359
//方法二:比上面的方法时间复杂度低,更好地剪枝,优化时间复杂度
319360
class Solution {
@@ -358,6 +399,7 @@ class Solution {
358399
}
359400
```
360401

402+
361403
## python
362404

363405
python2:

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /