mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Merge pull request #2081 from Lozakaka/patch-10
improving java solution by using stringBuilder
This commit is contained in:
@ -316,6 +316,47 @@ class Solution {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
//方法一:但使用stringBuilder,故优化时间、空间复杂度,因为向字符串插入字符时无需复制整个字符串,从而减少了操作的时间复杂度,也不用开新空间存subString,从而减少了空间复杂度。
|
||||||
|
class Solution {
|
||||||
|
List<String> result = new ArrayList<>();
|
||||||
|
public List<String> restoreIpAddresses(String s) {
|
||||||
|
StringBuilder sb = new StringBuilder(s);
|
||||||
|
backTracking(sb, 0, 0);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
private void backTracking(StringBuilder s, int startIndex, int dotCount){
|
||||||
|
if(dotCount == 3){
|
||||||
|
if(isValid(s, startIndex, s.length() - 1)){
|
||||||
|
result.add(s.toString());
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for(int i = startIndex; i < s.length(); i++){
|
||||||
|
if(isValid(s, startIndex, i)){
|
||||||
|
s.insert(i + 1, '.');
|
||||||
|
backTracking(s, i + 2, dotCount + 1);
|
||||||
|
s.deleteCharAt(i + 1);
|
||||||
|
}else{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
//[start, end]
|
||||||
|
private boolean isValid(StringBuilder s, int start, int end){
|
||||||
|
if(start > end)
|
||||||
|
return false;
|
||||||
|
if(s.charAt(start) == '0' && start != end)
|
||||||
|
return false;
|
||||||
|
int num = 0;
|
||||||
|
for(int i = start; i <= end; i++){
|
||||||
|
int digit = s.charAt(i) - '0';
|
||||||
|
num = num * 10 + digit;
|
||||||
|
if(num > 255)
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
//方法二:比上面的方法时间复杂度低,更好地剪枝,优化时间复杂度
|
//方法二:比上面的方法时间复杂度低,更好地剪枝,优化时间复杂度
|
||||||
class Solution {
|
class Solution {
|
||||||
@ -360,6 +401,7 @@ class Solution {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
## python
|
## python
|
||||||
|
|
||||||
回溯(版本一)
|
回溯(版本一)
|
||||||
|
Reference in New Issue
Block a user