• 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 且不能有前导零

  • 相关阅读:
    单据的多个状态字段
    Win7 如何阻止程序联网
    强制关机.bat
    Delphi Class of
    坐标转换 GetCursorPos与转换
    Delphi 的RTTI机制浅探-2
    Delphi 的RTTI机制浅探-1
    Delphi 的RTTI机制-3
    Delphi 的RTTI机制-2
    Delphi 的RTTI机制-1
  • 原文地址:https://www.cnblogs.com/GeniusYang/p/7544912.html
Copyright © 2020-2023  润新知