首页 > 代码库 > Restore IP Addresses
Restore IP Addresses
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> solutions = new ArrayList<String>(); restoreIp(s, solutions, 0, "", 0); return solutions;}private void restoreIp(String ip, List<String> solutions, int idx, String restored, int count) { if (count > 4) return; if (count == 4 && idx == ip.length()) solutions.add(restored); for (int i=1; i<4; i++) { if (idx+i > ip.length()) break; String s = ip.substring(idx,idx+i); if ((s.startsWith("0") && s.length()>1) || (i==3 && Integer.parseInt(s) >= 256)) continue; restoreIp(ip, solutions, idx+i, restored+s+(count==3?"" : "."), count+1); }}}
Restore IP Addresses
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。