Restore IP Addresses

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

Example

Given "25525511135", return

[
  "255.255.11.135",
  "255.255.111.35"
]

Order does not matter.

这题和排列题一样。先取IP中的第一个部分,然后递归得到后面IP部分,最后把他们合起来。但是里面有几个需要注意的test case。

 1 public class Solution {
 2     public List<String> restoreIpAddresses(String s) {
 3         List<String> list = new ArrayList<>();
 4         helper(list, s, "", 3);
 5         return list;
 6     }
 7     private void helper(List<String> result, String str, String temp, int dotsLeft) {
 8         if (dotsLeft == -1 && str.length() == 0) {
 9             result.add(temp);
10             return;
11         }
12         if (dotsLeft <= -1) return;
13         
14         for (int i = 1; i <= Math.min(str.length(), 3); i++) {
15             String firstPart = str.substring(0, i);
// 0.0.0.0 is valid 0.1.0.010 is invalid
16 if (i > 1 && firstPart.charAt(0) == '0' || Integer.parseInt(firstPart) > 255) break; 17 helper(result, str.substring(i), temp.length() == 0 ? firstPart : temp + "." + firstPart, dotsLeft - 1); 18 } 19 } 20 }
posted @ 2016-07-13 09:56  北叶青藤  阅读(201)  评论(0编辑  收藏  举报