import java.util.*; public class Solution { private ArrayList<String> res = new ArrayList<>(); /** * * @param s string字符串 * @return string字符串ArrayList */ public ArrayList<String> restoreIpAddresses (String s) { // write code here if (s == null || s.length() < 1) { return res; } dfs(s, 0, new ArrayList<>()); return res; } private void dfs(String s, int start, List<String> list) { if (start == s.length() && list.size() == 4) { res.add(list2Ip(list)); return; } for (int i = start; i < s.length(); i++) { if (i - start >= 1 && s.charAt(start) == '0') { break; } if (Integer.parseInt(s.substring(start, i + 1)) > 255) { break; } list.add(s.substring(start, i + 1)); dfs(s, i + 1, list); list.remove(list.size() - 1); } } private String list2Ip(List<String> list) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 3; i++) { sb.append(list.get(i)).append("."); } sb.append(list.get(3)); return sb.toString(); } }