93. Restore IP Addresses

来源:互联网 发布:mysql 博客 编辑:程序博客网 时间:2024/05/22 04:37

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)

Solution 1 Iterative

public List<String> restoreIpAddresses2(String s) {List<String> ans = new ArrayList<String>();int len = s.length();for (int i = 1; i <= 3; ++i) { // first cutif (len - i > 9)continue;for (int j = i + 1; j <= i + 3; ++j) { // second cutif (len - j > 6)continue;for (int k = j + 1; k <= j + 3 && k < len; ++k) { // third cutint a, b, c, d; // the four int's seperated by "."a = Integer.parseInt(s.substring(0, i));b = Integer.parseInt(s.substring(i, j)); // notice that "01" can be parsed to 1. Need to deal with that later.c = Integer.parseInt(s.substring(j, k));d = Integer.parseInt(s.substring(k));if (a > 255 || b > 255 || c > 255 || d > 255)continue;String ip = a + "." + b + "." + c + "." + d;if (ip.length() < len + 3)continue; // this is to reject those int's parsed from// "01" or "00"-like substringsans.add(ip);}}}return ans;}

Solution 2 Backtracking

//backtrackingpublic static List<String> restoreIpAddresses4(String s) {        List<String> res = new ArrayList<>();        helper(s,"",res,0);        return res;    }    public static void helper(String s, String tmp, List<String> res,int n){        if(n==4){            if(s.length()==0) res.add(tmp.substring(0,tmp.length()-1));            //substring here to get rid of last '.'            return;        }        for(int k=1;k<=3;k++){            if(s.length()<k) break;            int val = Integer.parseInt(s.substring(0,k));            if(val>255 || k!=String.valueOf(val).length()) continue;            /*in the case 010 the parseInt will return len=2 where val=10, but k=3, skip this.*/            helper(s.substring(k),tmp+s.substring(0,k)+".",res,n+1);        }    }


0 0
原创粉丝点击