zoukankan      html  css  js  c++  java
  • [LeetCode] 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)
    » Solve this problem

    [解题思路]
    递归的将数字串分成四个部分,每个部分满足0<=p<=255。要注意一些边界case,比如010是没有意思的,“0.10.010.1”。

    1:       vector<string> restoreIpAddresses(string s) {   
    2: vector<string> col;
    3: string ip;
    4: partitionIP(s, 0, 0, ip, col);
    5: return col;
    6: }
    7: void partitionIP(string s, int startIndex, int partNum,
    8: string resultIp, vector<string>& col)
    9: {
    10: //max: 3 bits per partition
    11: if(s.size() - startIndex > (4-partNum)*3) return;
    12: //min: 1 bit per partition
    13: if(s.size() - startIndex < (4-partNum)) return;
    14: if(startIndex == s.size() && partNum ==4)
    15: {
    16: resultIp.resize(resultIp.size()-1);
    17: col.push_back(resultIp);
    18: return;
    19: }
    20: int num =0;
    21: for(int i = startIndex; i< startIndex +3; i++)
    22: {
    23: num = num*10 + (s[i]-'0');
    24: if(num<=255)
    25: {
    26: resultIp+=s[i];
    27: partitionIP(s, i+1, partNum+1, resultIp+'.', col);
    28: }
    29: if(num ==0)//0.0.0.0 valid, but need to avoid 0.1.010.01
    30: {
    31: break;
    32: }
    33: }
    34: }



  • 相关阅读:
    Spark 基本概念及入门
    Cron 表达式详解
    VmWare 网络模式
    微信、支付宝各种支付退款
    Spring Security OAuth2 SSO 单点登录
    Git 入门详解
    基于Spring Boot 2.x 的 Spring Cloud Admin 实践
    Git 提交规范
    Linux 安装 Mysql8.0
    Docker入门
  • 原文地址:https://www.cnblogs.com/codingtmd/p/5078966.html
Copyright © 2011-2022 走看看