当前位置:网站首页>力扣练习——37 复原IP地址
力扣练习——37 复原IP地址
2022-08-02 04:18:00 【qq_43403657】
37 复原IP地址
1.问题描述
给定一个只包含数字的字符串,复原它(在中间插入点号)并返回所有可能的 IP 地址格式,输出可能的格式的数量。
有效的 IP 地址正好由四个整数(每个整数位于 0 到 255 之间)组成,整数之间用 ‘.’ 分隔。
示例:
输入: “25525511135”
输出: 2
说明:因为可能的IP地址包括:[“255.255.11.135”, “255.255.111.35”]
2.输入说明
输入一个只包含数字的字符串
3.输出说明
输出一个整数
4.范例
输入
25525511135
输出
2
5.代码
#include <iostream>
#include <queue>
#include <cstdlib>
#include <string>
#include<set>
using namespace std;
vector<string> ans;
vector<string> path; // 保存ip地址的每一个段
int n;
//检查IP段是否合法
bool check(string num) {
// 检测前导0
if (num.size() > 1 && num[0] == '0')
return false;
//stoi 实现string to integer
return stoi(num) <= 255; // 每个部分均小于等于255
}
void backtracking(string s, int start, int cnt) {
if (cnt == 4 && start == n) {
if (start < n) return; // 已经有四段了,但数字没有用完,剪枝
ans.push_back(path[0] + '.' + path[1] + '.' + path[2] + '.' + path[3]);
return;
}
for (int len = 1; len <= 3 && start + len - 1 < n; len++) {
// 每个数字部分位数 1-3
string num = s.substr(start, len);
if (check(num)) {
path.push_back(num);
backtracking(s, start + len, cnt + 1);
path.pop_back();
}
}
}
vector<string> restoreIpAddresses(string s)
{
n = s.size();
if (n > 12) return ans; // 最多12位
backtracking(s, 0, 0);
return ans;
}
int main()
{
vector<string>res;
string s;
cin >> s;
res = restoreIpAddresses(s);
cout << res.size() << endl;
return 0;
}
边栏推荐
猜你喜欢
随机推荐
A Practical Arrangement of Map GIS Development Matters (Part 1)
复制延迟案例(1)-最终一致性
力扣 剑指 Offer 56 - I. 数组中数字出现的次数
C语言:结构体总结
C程序调试过程常见的错误
数据复制系统设计(2)-同步复制与异步复制
P1192 台阶问题
递归实现组合型枚举(DAY 92)
【STM32】ADC采集光敏数据(不看库函数手册进行配置)
STM32 OLED显示屏--SPI通信知识汇总
CaDDN paper reading of monocular 3D target detection
Visual SLAM Lecture Fourteen - Lecture 13 Practice: Designing a SLAM system (the most detailed code debugging and running steps)
Minecraft 1.18.1、1.18.2模组开发 23.3D动画盔甲制作
RuoYi-App启动教程
The most authoritative information query steps for SCI journals!
学内核之四:关于内核与硬件的衔接
数据复制系统设计(3)-配置新的从节点及故障切换
多主复制下处理写冲突(1)-同步与异步冲突检测及避免冲突
无主复制系统(3)-Quorum一致性的局限性
立方体卫星Light-1









