• lintcode


     1 class Solution {
     2 public:
     3     /*
     4      * @param s: the IP string
     5      * @return: All possible valid IP addresses
     6      */
     7     vector<string> restoreIpAddresses(string &s) {
     8         // write your code here
     9         vector<string> ans;
    10         dfs(s, 0, ans, "", 0);
    11         return ans;
    12     }
    13     void dfs(string &s, int pos, vector<string> &ans, string res, int cnt){
    14         if(pos >= s.length() && cnt == 4){
    15                 ans.push_back(res);
    16                 return ;
    17         } else {
    18                 for(int i = 0; i <= 2; ++i){
    19                         if(pos + i < s.length()){
    20                                 string tmp = s.substr(pos, i + 1);
    21                                 int num = atoi(tmp.c_str());
    22                                 if((num == 0 && tmp.length() != 1) || (num != 0 && tmp[0] == '0')) continue;
    23                                 string nres = "";
    24                                 if(i == 2){
    25                                        if(num < 256){
    26                                         if(pos != 0)
    27                                                 nres = res + "." + tmp;
    28                                         else    nres = res + tmp;
    29                                         dfs(s, pos + i  + 1, ans, nres, cnt + 1);
    30                                        }
    31                                 } else {
    32                                         if(pos != 0)
    33                                                 nres = res + "." + tmp;
    34                                                 else nres = res + tmp;
    35                                         dfs(s, pos + i + 1, ans, nres, cnt + 1);
    36                                 }
    37                         }
    38                 }
    39         }
    40     }
    41 };

    ip地址的每个区域值不大于255 且不能有前导零

  • 相关阅读:
    c# 事件阻断
    正则语义化API
    c# 防止继承和单例
    Maxscript 控制流混淆
    3dmax快速安装补丁的方法
    c# 使用类中的方法更新自己
    Maxscript 变量作用域
    Maxscript 键值对
    Maxscript 数据结构和算法记录
    Datawhale 之NLP学习-打卡(五)
  • 原文地址:https://www.cnblogs.com/GeniusYang/p/7544912.html
Copyright © 2020-2023  润新知