给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
示例:
输入: "25525511135"
输出: ["255.255.11.135", "255.255.111.35"]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/restore-ip-addresses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
List<String> results;
StringBuilder sb;
char[] chars;
int n;
public List<String> restoreIpAddresses(String s) {
results = new ArrayList<>();
sb = new StringBuilder();
chars = s.toCharArray();
n = chars.length;
dfs(0, 0);
return results;
}
public void dfs(int count, int i){
if(count == 4 && i == n){
results.add(sb.toString());
return;
}
int remainCount = 4 - count;
int remainsChars = n - i;
if(remainCount > remainsChars || remainCount * 3 < remainsChars){
return;
}
int len = sb.length();
int maxLen = chars[i] == '0' ? 1 : 3;
for(int j = 0; j < maxLen && i + j < n; j++){
if (j == 2 && (chars[i] - '0') * 100 + (chars[i + 1] - '0') * 10 + chars[i + 2] - '0' > 255) {
return;
}
for(int k = 0; k <= j; k++){
sb.append(chars[i+k]);
}
if(count < 3){
sb.append('.');
}
dfs(count+1, i+j+1);
sb.delete(len, count < 3 ? len + j + 2: len + j + 1);
}
}
}