zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    nginx:安装成windows服务
    org.aspectj.apache.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 18
    数据库中间件
    架构策略
    谈判
    设计模式 总结 常用10种
    08 状态模式 state
    07 策略模式 strategy
    06 命令模式(不用)
    05 观察者模式 Observer
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3423745.html
Copyright © 2011-2022 走看看