码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode93:Restore IP Addresses

时间:2015-06-06 11:49:30      阅读:86      评论:0      收藏:0      [点我收藏+]

标签:

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)

思路:搜索DFS+剪枝

剪枝策略:IP为4个子串,递归4层即可。

技术分享
 1 public class Solution {
 2    public List<String> restoreIpAddresses(String s) {
 3             List<String> ans=new ArrayList<String>();
 4             if(s.length()==0) return ans;
 5             dfs(ans,s,0,"",1);
 6             return ans;
 7         }
 8 
 9      void dfs(List<String> ans, String s, int start, String string, int index) {
10         // TODO Auto-generated method stub
11          if(start>=s.length()){
12              return ;
13          }
14          if(index==4){
15              String sub=s.substring(start);
16              if(isValid(sub)){
17                  ans.add(string+"."+sub);
18              }
19              return;
20          }
21         for(int i=1;i<4&&((start+i)<=s.length());i++){
22             String sub=s.substring(start,start+i);
23             if(isValid(sub)){
24                 if(index==1){
25                     dfs(ans, s, start+i, sub, index+1);
26                 }else{
27                     dfs(ans, s, start+i, string+"."+sub, index+1);
28                 }
29             }
30         }
31     }
32 
33     private boolean isValid(String sub) {
34         // TODO Auto-generated method stub
35         if(sub.length()>=4) return false;
36         if(sub.charAt(0)==‘0‘&&sub.length()>1) return false;
37         int temp=Integer.parseInt(sub);
38         if(temp>=0&&temp<=255){
39             return true;
40         }
41         return false;
42     }
43 }
View Code

参考:http://blog.csdn.net/yangliuy/article/details/43915517

LeetCode93:Restore IP Addresses

标签:

原文地址:http://www.cnblogs.com/gonewithgt/p/4556234.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!