标签:
Code:
public class Solution { public List<String> restoreIpAddresses(String s) { List<String> list = new ArrayList<>(); int len = s.length(); if(len < 4) return list; String ip = ""; validIpAddresses(s, ip, 4, len, 0, list); return list; } public void validIpAddresses(String s, String ip, int n, int len, int pos, List<String> list){ int size = len - pos; if(size <= 0) return; if(n == 1){ if(size > 3) return; String block = s.substring(pos, pos+size); if(Integer.parseInt(block) > 255) return; if(size > 1 && s.charAt(pos) == ‘0‘) return; ip = ip + block; list.add(ip); return; } if(size > 3) size = 3; for(int i = 1; i <= size; i++){ String block = s.substring(pos, pos+i); if(i > 1 && s.charAt(pos) == ‘0‘) return; if(Integer.parseInt(block) > 255) return; validIpAddresses(s, ip + block +".", n-1, len, pos+i, list); } } }
Jan 24 - Restore Ip Addresses; BackTracking; Recursion; DFS;
标签:
原文地址:http://www.cnblogs.com/5683yue/p/5156505.html