题目:
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given "25525511135"
,
return ["255.255.11.135", "255.255.111.35"]
. (Order does not matter)
这个题,我觉得主要考察的是细节吧。因为我就漏了一个test case。 我错在:
Input: | "010010" |
Output: | ["0.1.0.010","0.1.00.10","0.1.001.0","0.10.0.10","0.10.01.0","0.100.1.0","01.0.0.10","01.0.01.0","01.00.1.0","010.0.1.0"] |
Expected: | ["0.10.0.10","0.100.1.0"] |
思路上直接想到DFS。就用DFS解了。
1 public List<String> restoreIpAddresses(String s) { 2 List<String> res = new ArrayList<String>(); 3 if (s == null || s.length() == 0) { 4 return res; 5 } 6 helper(0, 1, "", s, res); 7 return res; 8 } 9 10 private void helper(int index, int seg, String temp, String s, List<String> res) { 11 if (index >= s.length()) { 12 return; 13 } 14 if (seg == 4) { 15 if (isValid(s.substring(index))) { 16 temp += s.substring(index); 17 res.add(temp); 18 }else{ 19 return; 20 } 21 } 22 for (int i = 1; i < 4; i++) { 23 if (index + i < s.length() && isValid(s.substring(index, index + i))) { 24 helper(index + i, seg + 1, temp + s.substring(index, index + i) + ".", s, res); 25 }else{ 26 return; 27 } 28 } 29 } 30 31 private static boolean isValid(String s) { 32 if (s.length() <= 0 || s.length() > 3) { 33 return false; 34 } 35 if (s.charAt(0) == '0' && s.length() != 1) { 36 return false; 37 } 38 int n = Integer.parseInt(s); 39 if (n < 0 || n > 255) { 40 return false; 41 } 42 return true; 43 } 44