zoukankan      html  css  js  c++  java
  • LeetCode OJ:Restore IP Addresses(存储IP地址)

    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)

    典型的dfs,但是要点是注意什么才是真的ip地址,代码如下:

     1 class Solution {
     2 public:
     3     vector<string> restoreIpAddresses(string s) {
     4         if (s.size() > 12) return ret;
     5         dfs(s, 0, 0);
     6         return ret;
     7     }
     8     
     9     bool check(string &s)
    10     {
    11         if (s.size() == 1)
    12             return "0" <= s && s <= "9";
    13         else if (s.size() == 2)
    14             return "10" <= s && s <= "99";
    15         else if (s.size() == 3)
    16             return "100" <= s && s <= "255";
    17         else
    18             return false;
    19     }
    20 
    21     void dfs(const string & s, int start, int nth)
    22     {
    23         if (nth == 4 && start != s.size())
    24             return;
    25         else if (nth == 4 && start == s.size()){
    26             string tmp = "";
    27             for (int i = 0; i < 3; ++i){
    28                 tmp += tmpRes[i];
    29                 tmp += ".";
    30             }
    31             tmp += tmpRes[3];    //为了凑格式
    32             ret.push_back(tmp);
    33         }
    34         else
    35             for (int i = 1; i < 4; ++i){
    36                 if(start + i <= s.size()){
    37                     string tmp = s.substr(start, i);
    38                     if(check(tmp)){
    39                         tmpRes.push_back(tmp);
    40                         dfs(s, start + i, nth + 1);
    41                         tmpRes.pop_back();
    42                     }
    43                 }
    44             }
    45     }
    46 
    47 private:
    48     vector<string> tmpRes;
    49     vector<string> ret;
    50 };

    写的有点乱了 ,见谅见谅

  • 相关阅读:
    drf 权限流程解析
    drf 认证流程解析
    drf 版本解析
    Django REST framework初识
    RESTful规范
    Flask框架
    Flask框架解析目录
    hdu
    hdu 6113 度度熊的01世界(结构体的赋值问题)
    hdu 6114 chess(排列组合)
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4953672.html
Copyright © 2011-2022 走看看