93. Restore IP Addresses
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了93. Restore IP Addresses相关的知识,希望对你有一定的参考价值。
Given a string containing only digits, restore it by returning all possible valid IP address combinations. For example: Given "25525511135", return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)
什么时候临时容器符合题意加入结果容器, 和容器中字符串的存在形式
if (list.size() == 4) { if (start != s.length()) { return; }
什么时候加入临时容器, 对特殊情况的处理:
private boolean isValid(String s) { if (s.charAt(0) == ‘0‘) { return s.equals("0"); } int digit = Integer.valueOf(s); return digit >= 0 && digit <= 255; }
public class Solution { /** * @param s the IP string * @return All possible valid IP addresses */ public ArrayList<String> restoreIpAddresses(String s) { // Write your code here ArrayList<String> res = new ArrayList<String>(); ArrayList<String> list = new ArrayList<String>(); if (s == null || s.length() == 0) { return res; } helper(res, s, list, 0); return res; } private void helper( ArrayList<String> res, String s, ArrayList<String> list, int start) { if (list.size() == 4) { if (start != s.length()) { return; } StringBuilder sb = new StringBuilder(); for (String tmp : list) { sb.append(tmp); sb.append("."); } sb.deleteCharAt(sb.length() - 1); res.add(sb.toString()); return; } for (int i = start; i < s.length() && i < start + 3; i++) { String item = s.substring(start, i + 1); if (isValid(item)) { list.add(item); helper(res, s, list, i + 1); list.remove(list.size() - 1); } } } private boolean isValid(String s) { if (s.charAt(0) == ‘0‘) { return s.equals("0"); } int digit = Integer.valueOf(s); return digit >= 0 && digit <= 255; } }
以上是关于93. Restore IP Addresses的主要内容,如果未能解决你的问题,请参考以下文章