zoukankan      html  css  js  c++  java
  • LeetCode93 Restore IP Addresses

    题目:

    Given a string containing only digits, restore it by returning all possible valid IP address combinations. (Medium)

    For example:
    Given "25525511135",

    return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)

    分析:

    使用回溯法即可。helper函数用来处理DFS过程,isValid判断一个子串是否符合IP地址一个点分十进制的一块。

    注意在isValid中要除去类似00,01这种0打头的情况。

    代码:

     1 class Solution {
     2 private:
     3     vector<string> result;
     4     bool isValid(const string& s) {
     5         if (s[0] == '0' && s.size() > 1) {  // for case like "00.122.122.122"
     6             return false;
     7         }
     8         int num = stoi(s);
     9         if (num >= 0 && num <= 255) {
    10             return true;
    11         }
    12         return false;
    13     }   
    14     void helper(const string& s, string curS, int start, int step) {
    15         if (step == 4) {
    16             if (start != s.size()) {
    17                 return;
    18             }
    19             curS.pop_back();
    20             result.push_back(curS);
    21             return;
    22         }
    23         for (int i = 1; i <= 3; ++i) {
    24             if (start + i <= s.size()) {
    25                 string tempS = s.substr(start, i);
    26                 if (isValid(tempS)) {
    27                     string newS = curS + tempS;
    28                     newS.push_back('.');
    29                     helper(s, newS, start + i, step + 1);
    30                 }                
    31             }
    32         }
    33     }
    34 public:
    35     vector<string> restoreIpAddresses(string s) {
    36         string curS;
    37         helper(s, curS, 0, 0);
    38         return result;
    39     }
    40 };
  • 相关阅读:
    142. 环形链表 II
    59. 螺旋矩阵 II
    996. 正方形数组的数目
    1323. 6 和 9 组成的最大数字
    面试题 17.14. 最小K个数
    389. 找不同
    1103. 分糖果 II
    背景透明度
    css3-新属性-用户界面
    响应式布局-基础结构
  • 原文地址:https://www.cnblogs.com/wangxiaobao/p/5994580.html
Copyright © 2011-2022 走看看