NO.93 复原IP地址 中等
思路一:回溯 暴力尝试不同的ip段分割方式,保存符合要求的。
一个正确的IP地址最基本的格式:四段、每段在[0,255]区间内、每段不以0开头。
不啰嗦了,直接看代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| List<String> res = new ArrayList<>(); public List<String> restoreIpAddresses(String s) { if (s == null || s.length() < 4 || s.length() > 12) return res; dfs(0, "", 4, s); return res; }
private void dfs(int curLen, String combination, int del, String s) { if (curLen == s.length() && del == 0) { res.add(combination.substring(0, combination.length() - 1)); return; } if (del < 0) return; for (int j = curLen; j < curLen + 3; j++) { if (j < s.length()) { if (j == curLen && s.charAt(j) == '0'){ dfs(j + 1, combination + s.charAt(j) + '.', del - 1, s); break; } if (Integer.parseInt(s.substring(curLen, j + 1)) <= 255) dfs(j + 1, combination + s.substring(curLen, j + 1)+'.', del - 1, s); } } }
|
本人菜鸟,有错误请告知,感激不尽!
更多题解和源码:github