LeetCode93 复原 IP 地址

前言

题目: 93. 复原 IP 地址
文档: 代码随想录------复原 IP 地址
编程语言: C++
解题状态: 没思路...

思路

依旧是切割问题,但同时还需要操作字符串添加逗号作为分隔符,并验证区间的合法性。

代码

cpp 复制代码
class Solution {
private:
    vector<string> res;
    void backtracking(string& s, int startIndex, int pointNum) {
        if (pointNum == 3) {
            if (isVaild(s, startIndex, s.size() - 1)) {
                res.push_back(s);
            }
            return;
        }

        for (int i = startIndex; i < s.size(); i++) {
            if (isVaild(s, startIndex, i)) {
                s.insert(s.begin() + i + 1, '.');
                pointNum++;
                backtracking(s, i + 2, pointNum);
                pointNum--;
                s.erase(s.begin() + i + 1);
            } else break;
        }
    }

    bool isVaild(const string& s, int start, int end) {
        if (start > end) {
            return false;
        }

        if (s[start] == '0' && start != end) {
            return false;
        }

        int num = 0;
        for (int i = start; i <= end; i++) {
            if (s[i] > '9' || s[i] < '0') {
                return false;
            }
            num = num * 10 + (s[i] - '0');
            if (num > 255) {
                return false;
            }
        }

        return true;
    }
public:
    vector<string> restoreIpAddresses(string s) {
        res.clear();
        if (s.size() < 4 || s.size() > 12) return res;
        backtracking(s, 0, 0);
        return res;
    }
};
  • 时间复杂度: O ( 3 4 ) O(3^4) O(34),IP地址最多包含4个数字,每个数字最多有3种可能的分割方式,则搜索树的最大深度为4,每个节点最多有3个子节点。
  • 空间复杂度: O ( n ) O(n) O(n)
相关推荐
文丑颜不良啊14 小时前
LeetCode3421~3440题目解析
java·leetcode
cjz389915 小时前
双指针技巧:覆盖式双指针(原地覆盖)
算法
whitelbwwww16 小时前
cuBLAS--CUDA高性能线性代数计算库--第一部分
c++·线性代数·gpu算力·cuda c++
console.log('npc')18 小时前
Python 学习教程 · 第4课:数据结构
数据结构·python·学习
eggwyw18 小时前
C++设计模式之解释器模式
开发语言·c++
橘子1319 小时前
【高级数据库】关系代数基本概念
算法
电科_银尘1 天前
【大模型算法与工程 15】手写Self-Attention:Q、K、V与缩放点积
算法
我不会插花弄玉1 天前
13.多路转接epoll【由浅入深-网络】
网络·c++·epoll
郝学胜-神的一滴1 天前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
秋天的怀念_David1 天前
算法一千零一夜 · 第三十三夜 · 跳表
java·程序人生·算法