标签:
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处理,最多就4层递归,因为ip最多就是由4个数组成的。
public class Solution { public List<String> restoreIpAddresses(String s) { List<String> result = new ArrayList<String>(); if (s.length() < 4 || s.length() > 15) return result; List<String> tmp = new ArrayList<String>(); dfs(result, tmp, 0, 0, s); return result; } private void dfs(List<String> result, List<String> tmp, int dep, int cur, String s) { if (dep >= 4) { if (cur == s.length()) { StringBuilder ans = new StringBuilder(); ans.append(tmp.get(0)); for (int i = 1; i < 4; i++) ans.append("." + tmp.get(i)); result.add(ans.toString()); } return; } for (int k = 1; k <= 3 && cur+(k-1) < s.length(); k++) { String num = s.substring(cur, cur+k); if (isValid(num)) { tmp.add(num); dfs(result, tmp, dep+1, cur+k, s); tmp.remove(tmp.size()-1); } } } private boolean isValid(String num) { if (num.length() == 1 && num.compareTo("0") >= 0 && num.compareTo("9") <= 0) return true; if (num.length() == 2 && num.compareTo("10") >= 0 && num.compareTo("99") <= 0) return true; if (num.length() == 3 && num.compareTo("100") >= 0 && num.compareTo("255") <= 0) return true; return false; } }
标签:
原文地址:http://blog.csdn.net/u011345136/article/details/45171215