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)
分析: 主要是validate的问题。
public class Solution { public List<String> restoreIpAddresses(String s) { List<String> res = new ArrayList<>(); String item = new String(); dfs(res, item , 0 , s); return res; } public void dfs(List<String> res , String item, int deep , String s){ if(deep == 3 && isValid(s)){ res.add(item + s); return; } for(int i = 0 ; i < 3 && i < s.length() ; i++){ String sub = s.substring(0 , i+1); if(isValid(sub)){ dfs(res , item + sub + ".", deep+1, s.substring(i+1, s.length())); } } } public boolean isValid(String s){ if(s.charAt(0) == '0') return s.equals("0"); int num = Integer.parseInt(s); if(num > 0 && num < 255) return true; return false; } }