回溯法
class Solution {
static final int SEC_COUNT = 4;
List<String> ans = new ArrayList<>();
int[] segments = new int[SEC_COUNT];
public List<String> restoreIpAddresses(String s) {
dfs(s, 0, 0);
return ans;
}
private void dfs(String s, int segId, int segStart) {
if (segId == SEC_COUNT && segStart == s.length()) {
StringBuffer ipAddr = new StringBuffer();
for (int i = 0; i < SEC_COUNT; i++) {
ipAddr.append(segments[i]);
if (i != SEC_COUNT - 1) {
ipAddr.append(".");
}
}
ans.add(ipAddr.toString());
return;
}
if (segStart == s.length() || segId == SEC_COUNT)
return;
if (s.charAt(segStart) == '0') {
segments[segId] = 0;
dfs(s, segId + 1, segStart + 1);
}
int addr = 0;
for (int segEnd = segStart; segEnd < s.length(); segEnd++) {
addr = addr * 10 + (s.charAt(segEnd) - '0');
if (addr > 0 && addr <= 0xFF) {
segments[segId] = addr;
dfs(s, segId + 1, segEnd + 1);
} else {
break;
}
}
}
}