leetcode--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)

[java]  view plain  copy
  1. public class Solution {  
  2.     public List<String> restoreIpAddresses(String s) {  
  3.         List<String> res = new ArrayList<String>();       
  4.         if(s.equals("")) return res;  
  5.         Stack<String> stack = new Stack<String>();  
  6.         helper(s, 4, res, stack);             
  7.         return res;  
  8.     }  
  9.       
  10.     void helper(String s,int count,List<String> res,Stack<String> stack){  
  11.         if(count==0){             
  12.             if(s.length()==0){                
  13.                 String str = "";                  
  14.                 for(int i=0;i<stack.size();i++){  
  15.                     str += ".";  
  16.                     str += stack.get(i);  
  17.                 }                                 
  18.                 res.add(str.substring(1));  
  19.                 return;  
  20.             }else{  
  21.                 return;   
  22.             }  
  23.         }else{  
  24.             for(int i=1;i<4;i++){  
  25.                 if(s.length()>=i&&Integer.valueOf(s.substring(0,i))<=255){  
  26.                     if(i==1||(i>=2&&s.charAt(0)!='0')){  
  27.                         stack.add(s.substring(0,i));  
  28.                         helper(s.substring(i), count-1, res, stack);  
  29.                         stack.pop();  
  30.                     }  
  31.                 }  
  32.             }  
  33.         }  
  34.     }  
  35. }

原文链接http://blog.csdn.net/crazy__chen/article/details/46445081

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值