Leetcode探索——字节跳动·挑战字符串:复原IP地址
给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
示例:
输入: "25525511135" 输出: ["255.255.11.135", "255.255.111.35"]
算法思路:深度搜索,分别以每个长度为1,2,3组合成数字为其中一个IP数值。判断规则:①0<=IP数值<=255;②不允许IP数值为"0X",如“00”,“01”这些;③只能分割成4个IP数值,假如有4个IP数值后还有剩余字符,则直接返回。④用HashSet<String>把结果去重。
代码:
1 import java.util.ArrayList; 2 import java.util.HashSet; 3 import java.util.Iterator; 4 import java.util.List; 5 import java.util.Set; 6 7 class Solution { 8 public List<String> restoreIpAddresses(String s) { 9 Set<String> set = new HashSet<String>(); 10 List<String> list = new ArrayList<String>(); 11 if(s == null || "".equals(s)) { 12 return list; 13 } 14 dfsIP(s.toCharArray(), 0, 0, set, new int[4], 0); 15 for(Iterator<String> ite = set.iterator();ite.hasNext();) { 16 list.add(ite.next()); 17 } 18 return list; 19 } 20 21 public void dfsIP(char str[], int left, int len, Set<String> set, int tmp[],int depth) { 22 if(len > 3 || depth > 4 || left + len > str.length || (str[left]=='0' && len > 1)) { 23 return; 24 } 25 if(depth > 0) { 26 int num = Integer.valueOf(new String(str, left, len)); 27 if(num > 255 || num < 0) { 28 return; 29 } 30 if(left + len == str.length && depth == 4) { 31 //完了 32 String tStr = tmp[0] +"." + tmp[1] + "." + tmp[2] + "." + num; 33 set.add(tStr); 34 } 35 tmp[depth-1] = num; 36 } 37 for(int i = 1; i <= 3; i++) { 38 dfsIP(str, left+len, i, set, tmp, depth + 1); 39 } 40 } 41 }

浙公网安备 33010602011771号