Leetcode 93.複製IP地址
阿新 • • 發佈:2018-12-23
複製IP地址
給定一個只包含數字的字串,復原它並返回所有可能的 IP 地址格式。
示例:
輸入: "25525511135"
輸出: ["255.255.11.135", "255.255.111.35"]
1 import java.util.ArrayList; 2 import java.util.List; 3 4 class Solution { 5 private List<String> result = new ArrayList<>(); 6 int length; 7 publicList<String> restoreIpAddresses(String s) { 8 length = s.length(); 9 int[] ip = new int[4]; 10 restoreIpAddresses(s,0,ip,0); 11 return result; 12 } 13 private void restoreIpAddresses(String s, int si, int[] ip, int pi) { 14 int sl = length - si , pl = 3 - pi , i = -1;15 String pfx = null; 16 while (si< length){ 17 int num = s.charAt(si++) - '1' + 1; 18 if (i==0) break; 19 i = i == -1 ? num : i * 10 + num; 20 sl--; 21 if (i>255) break; 22 if (sl < pl || sl > pl * 3) continue; 23 if (pi==3){ 24 if (pfx==null){ 25 StringBuilder pfxBuilder = new StringBuilder(); 26 for (int j = 0; j < ip.length-1; j++) pfxBuilder.append(ip[j]).append('.'); 27 pfx = pfxBuilder.toString(); 28 } 29 result.add(pfx + i); 30 } 31 ip[pi] = i; 32 restoreIpAddresses(s,si,ip,pi+1); 33 } 34 } 35 } 36