首页 > 代码库 > 93. Restore IP Addresses

93. Restore IP Addresses

题目:

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)

链接: http://leetcode.com/problems/restore-ip-addresses/

6/4/2017

6ms, 31%

照着别人改的。注意的问题:

1. restore里面不需要2重循环,直接用i从pos到pos + 3就可以了

2. 第28-30行判断leading 0的方法不错

 1 public class Solution {
 2     public List<String> restoreIpAddresses(String s) {
 3         List<String> ret = new ArrayList<>();
 4         List<String> list = new ArrayList<>();
 5         restore(s, ret, 0, list);
 6         return ret;
 7     }
 8     private void restore(String s, List<String> ret, int index, List<String> list) {
 9         if (list.size() == 4) {
10             if (index == s.length()) {
11                 ret.add(new String(String.join(".", list)));
12             }
13             return;
14         }
15         for (int i = index; i < s.length() && i <= index + 3; i++) {
16             String tmp = s.substring(index, i + 1);
17             if (isValid(tmp)) {
18                 list.add(tmp);
19                 restore(s, ret, i + 1, list);
20                 list.remove(list.size() - 1);
21             }
22         }
23     }
24     private boolean isValid(String s) {
25         if (s == null || s.length() == 0) {
26             return false;
27         }
28         if (s.charAt(0) == ‘0‘) {
29             return s.length() == 1;
30         }
31         int num = Integer.parseInt(s);
32         if (num < 0 || num >= 256) {
33             return false;
34         }
35         return true;
36     }
37 }

别人的答案:

三重循环

https://discuss.leetcode.com/topic/3919/my-code-in-java

更多讨论

https://discuss.leetcode.com/category/101/restore-ip-addresses

93. Restore IP Addresses