A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0
and 255
(inclusive) and cannot have leading zeros.
- For example,
"0.1.2.201"
and"192.168.1.1"
are valid IP addresses, but"0.011.255.245"
,"192.168.1.312"
and"192.168@1.1"
are invalid IP addresses.
Given a string s
containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s
. You are not allowed to reorder or remove any digits in s
. You may return the valid IP addresses in any order.
Example 1:
Input: s = "25525511135" Output: ["255.255.11.135","255.255.111.35"]
Example 2:
Input: s = "0000" Output: ["0.0.0.0"]
Example 3:
Input: s = "101023" Output: ["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]
Constraints:
0 <= s.length <= 20
s
consists of digits only.
题目链接:https://leetcode.com/problems/restore-ip-addresses/
题目大意:给一些数字字符串,求从中可以提取出多少合法的ip地址
题目分析:dfs即可
2ms,时间击败87%
class Solution {
List<String> ans;
public void dfs(char[] s, int pos, int n, int cnt, int[] cur) {
if (cnt == 4) {
if (pos == n) {
StringBuffer sb = new StringBuffer("");
for (int i = 0; i < cnt - 1; i++) {
sb.append(cur[i]).append(".");
}
sb.append(cur[3]);
ans.add(sb.toString());
}
return;
}
if (pos >= n) {
return;
}
if (s[pos] == '0') {
cur[cnt] = 0;
dfs(s, pos + 1, n, cnt + 1, cur);
return;
}
int num = 0;
for (int i = pos; i < Math.min(pos + 3, n); i++) {
num = num * 10 + (s[i] - '0');
if (num > 0 && num < 256) {
cur[cnt] = num;
dfs(s, i + 1, n, cnt + 1, cur);
}
}
}
public List<String> restoreIpAddresses(String s) {
char[] str = s.toCharArray();
ans = new ArrayList<>();
dfs(str, 0, str.length, 0, new int[4]);
return ans;
}
}