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 39 40 41 42
| class Solution { public List<String> restoreIpAddresses(String s) { List<String> resultList = new ArrayList<>(); List<Integer> numList = new ArrayList<>(4); backtrack(resultList, numList, s, 0); return resultList; }
private void backtrack(List<String> resultList, List<Integer> numList, String s, int startIndex) { if (numList.size() > 4) { return; } if (startIndex == s.length()) { if (numList.size() == 4) { StringBuilder sb = new StringBuilder(); for (Integer num : numList) { sb.append(num).append('.'); } sb.deleteCharAt(sb.length() - 1); resultList.add(sb.toString()); } return; }
if (s.charAt(startIndex) == '0') { numList.add(0); backtrack(resultList, numList, s, startIndex + 1); numList.remove(numList.size() - 1); } else { int num = 0; for (int endIndex = startIndex; endIndex < Math.min(startIndex + 3, s.length()); endIndex++) { num = num * 10 + (s.charAt(endIndex) - '0'); if (num <= 255) { numList.add(num); backtrack(resultList, numList, s, endIndex + 1); numList.remove(numList.size() - 1); } } } } }
|
注意对 0 的特殊处理及 IP 地址必须由 4 个数字组成。
References
93. Restore IP Addresses
剑指 Offer II 087. 复原 IP