标签:
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> results = new ArrayList<String>(); restoreIpAddresses(results, s, 0, 0, new LinkedList<String>()); return results; } private void restoreIpAddresses(List<String> results, String s, int from, int count, Deque<String> current) { if (count == 4) { if (from == s.length()) { //at the end of string StringBuilder sb = new StringBuilder(); for (String currentNum : current) { sb.append(currentNum); sb.append("."); } sb.setLength(sb.length() - 1); results.add(sb.toString()); } return; } for (int len = 1; len <= 3; ++len) { int end = from + len; if(end>s.length()) return; String num = s.substring(from, end); boolean valid = isValid(num); if (!valid) continue; current.add(num); restoreIpAddresses(results, s, from + len, count + 1, current); current.removeLast(); } } private boolean isValid(String s) { if (s.length() > 3 || s.length() == 0 || (s.charAt(0) == ‘0‘ && s.length() > 1) || Integer.parseInt(s) > 255) return false; return true; } }
标签:
原文地址:http://www.cnblogs.com/neweracoding/p/5702217.html