93. 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)
题目含义:给定一个数字字符串,给出所有可能的IPV4地址
思路:[0,i),[i,j),[j,k),[k,s.length()-1)
由于s.substring(i,j)是包含位置i的字符而不包含位置j的字符,所以(1<=i<4),由于i的后面要至少保留两位给j和k,所以i<s.length()-2
j在i的后面1-3位,所以 i+1 <= j < i+4,由于j后面至少要保留1位给k,所以j<i<s.length()-1
k在j的后面1-3位,所以 j+1 <= k < j+4,由于k后面可以为空,所以保证数组不越界就可以了k<s.length()
1 private boolean isValid(String num) { 2 if (num.isEmpty() || num.length() > 3 || (num.charAt(0) == '0' && num.length() > 1) || Integer.parseInt(num) > 255) 3 return false; 4 return true; 5 } 6 7 public List<String> restoreIpAddresses(String s) { 8 List<String> result = new ArrayList<>(); 9 for (int i = 1; i < 4 && i < s.length() - 2; i++) { 10 for (int j = i + 1; j < i + 4 && j < s.length() - 1; j++) 11 for (int k = j + 1; k < j + 4 && k < s.length(); k++) { 12 13 String s0 = s.substring(0, i); 14 String s1 = s.substring(i, j); 15 String s2 = s.substring(j, k); 16 String s3 = s.substring(k, s.length()); 17 if (isValid(s0) && isValid(s1) && isValid(s2) && isValid(s3)) { 18 result.add(s0 + "." + s1 + "." + s2 + "." + s3); 19 } 20 } 21 } 22 return result; 23 }