复原IP地址
作者:互联网
/** * 返回 所有的 有效的 IP 地址 */ class Solution { int count = 4; List<String> segments = new LinkedList<>(); List<String> result; public List<String> restoreIpAddresses(String s) { result = new ArrayList<String>(); backtrack(s, 0, 0); return result; } public void backtrack(String s, int startIndex, int pointNum) { // 明确分割为四段 故不能用startIndex移动到s的尾部作为回溯停止的标准 if (pointNum == count) { if (startIndex == s.length()) { StringBuilder ipAddress = new StringBuilder(); for (int i = 0; i < count; i++) { ipAddress.append(segments.get(i)); if (i != count - 1) { ipAddress.append("."); } } result.add(ipAddress.toString()); } return ; } for (int i = startIndex; i < s.length(); i++) { if (!isValid(s, startIndex, i)) continue; // 判断[startIndex, i]是否为合法字段 segments.add(s.substring(startIndex, i+1)); pointNum ++; backtrack(s, i + 1, pointNum); pointNum --; segments.remove(segments.size() - 1); } } // 判断s[startIndex, i]区间的字符串是否为合理 public boolean isValid(String s, int left, int right) { if (left > right) return false; if (s.charAt(left) == '0' && left != right) return false; // 除了"0" 其余不能以"0"开头 int num = 0; for (int i = left; i <= right; i++) { if (s.charAt(i) > '9' || s.charAt(i) < '0') return false; num = num * 10 + (int)(s.charAt(i) - '0'); if (num > 255) return false; } return true; } }
标签:pointNum,return,int,segments,startIndex,IP地址,复原,left 来源: https://www.cnblogs.com/xiazhenbin/p/16152399.html