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)
- public class Solution {
- public List<String> restoreIpAddresses(String s) {
- List<String> res = new ArrayList<String>();
- if(s.equals("")) return res;
- Stack<String> stack = new Stack<String>();
- helper(s, 4, res, stack);
- return res;
- }
-
- void helper(String s,int count,List<String> res,Stack<String> stack){
- if(count==0){
- if(s.length()==0){
- String str = "";
- for(int i=0;i<stack.size();i++){
- str += ".";
- str += stack.get(i);
- }
- res.add(str.substring(1));
- return;
- }else{
- return;
- }
- }else{
- for(int i=1;i<4;i++){
- if(s.length()>=i&&Integer.valueOf(s.substring(0,i))<=255){
- if(i==1||(i>=2&&s.charAt(0)!='0')){
- stack.add(s.substring(0,i));
- helper(s.substring(i), count-1, res, stack);
- stack.pop();
- }
- }
- }
- }
- }
- }
原文链接http://blog.csdn.net/crazy__chen/article/details/46445081