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
| public List<String> restoreIpAddresses(String s) { List<String> result = new ArrayList<>(); if (s == null || s.length() == 0) { return result; } search(s.toCharArray(), 0,0, "", result); return result; } private void search(char[] chars, int index, int fields, String cur, List<String> result) { if (fields == 4 && index == chars.length) { result.add(cur.substring(0, cur.length() - 1)); return; } if (fields == 4 || index == chars.length) { return; } if (chars[index] == '0') { search(chars, index + 1, fields + 1, cur + new String(chars, index, 1) + ".", result); } else { if (index + 2 < chars.length && Integer.parseInt(new String(chars, index, 3)) <= 255) { search(chars, index + 3, fields + 1, cur + new String(chars, index, 3) + ".", result); } if (index + 1 < chars.length) { search(chars, index + 2, fields + 1, cur + new String(chars, index, 2) + ".", result); } search(chars, index + 1, fields + 1, cur + new String(chars, index, 1) + ".", result); } }
|