• 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)

    Solution:

    注意这里if(tmp < 256 && tmp.toString().equals(s.substring(pos, pos + j)))

    如果不加tmp.toString().equals(s.substring(pos, pos + j)), 则可能会出现001 这种情况, 即高位为0.

     1 public class Solution {
     2     ArrayList<String> result = null;
     3     public ArrayList<String> restoreIpAddresses(String s) {
     4         // IMPORTANT: Please reset any member data you declared, as
     5         // the same Solution instance will be reused for each test case.
     6         result = new ArrayList<String>();
     7         getAddress(s, 0, 4, new StringBuffer());
     8         return result;
     9     }
    10     public void getAddress(String s, int pos, int num, StringBuffer sb){
    11         if(num == 0 || pos == s.length()){
    12             if(pos == s.length() && num == 0){
    13                 result.add(sb.substring(0, sb.length() - 1));
    14             }
    15             return;
    16         }
    17         for(int j = 1; j < 4 && pos + j <= s.length(); j ++){
    18             Integer tmp = Integer.valueOf(s.substring(pos, pos + j));
    19             if(tmp < 256 && tmp.toString().equals(s.substring(pos, pos + j))){
    20                 sb.append(s.substring(pos, pos + j));
    21                 sb.append(".");
    22                 getAddress(s, pos + j, num - 1, sb);
    23                 sb.delete(sb.length() - j - 1, sb.length());
    24             }
    25         }
    26     }
    27 }
  • 相关阅读:
    slice()与splice()
    apply和call函数
    参数arguments
    获取用户当前位置并设为中心点
    数组中元素为对象形式的去重
    判断浏览器环境(微信、支付宝)
    h5车牌号输入键盘
    点击事件的延迟
    jQuery修改伪元素
    webSocket认识
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3423745.html
Copyright © 2020-2023  润新知