题解 | 数字字符串转化成IP地址
数字字符串转化成IP地址
https://www.nowcoder.com/practice/ce73540d47374dbe85b3125f57727e1e
import java.util.*; public class Solution { public ArrayList<String> total = new ArrayList<>(); /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return string字符串ArrayList */ public ArrayList<String> restoreIpAddresses (String s) { // ArrayList<String> arrayList = new ArrayList<>(); if (s.length() < 4) { return total; } // // write code here // dealIpStr(s, 0, 0, new LinkedList<>(), arrayList); // return arrayList; chageStr(s,new LinkedList(),0); return total; } public void chageStr(String str,LinkedList<String> items,Integer max) { if (items.size() == 3) { if (max >= str.length()) { return; } String substring = str.substring(max); if (substring.startsWith("0") && !substring.equals("0")) { return; } if (substring.length() >3) { return; } int i = Integer.parseInt(substring); if (i>255) { return; } total.add(String.join(".",items) + "." + substring); return; } for (int i = 1; i <= 3; i++) { if ( max + i > str.length()) { continue; } String substring = str.substring(max, max + i); if (substring.startsWith("0") && !substring.equals("0")) { continue; } if (Integer.parseInt(substring) > 255) { continue; } items.add(substring); chageStr(str, items, max + i); items.removeLast(); } } public void dealIpStr(String s, int index,Integer count, LinkedList<String> list,ArrayList<String> arrayList) { if (count >= 3) { if (index<= s.length()-1) { String last = s.substring(index, s.length()); if (last.length() > 1&& last.startsWith("0")) { return; } Integer lastI = new Integer(last); if ( lastI>=0 && lastI <= 255) { StringBuilder builder = new StringBuilder(); for (String i : list) { builder.append(i); builder.append("."); } builder.append(lastI); arrayList.add(builder.toString()); } } return; } for (int i=1;i<=3;i++) { if ( index + i > s.length() ) { return; } String sub = s.substring(index, index + i); if (sub.length() > 1 && sub.startsWith("0")) { return; } if (index+i < s.length() && sub != "" && new Integer(sub) >= 0 && new Integer(sub)<= 255) { list.add(sub); dealIpStr(s,index+i,count+1,list,arrayList); list.removeLast(); } } } }