当前位置:网站首页>力扣练习——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;
}
边栏推荐
猜你喜欢

PyQt5_pyqtgraph鼠标在折线图上画直线

Learn about the sequential storage structure of binary tree - heap

洛谷P2437蜜蜂路线

CaDDN code debugging

日本痴汉打赏女主播1.5亿,结果。。。

Minecraft 1.18.1, 1.18.2 module development 23.3D animation armor production

W25Q16 存储器(Flash)

STM32 OLED显示屏--SPI通信知识汇总

batch_size of deep learning foundation

C语言:结构体总结
随机推荐
A practice arrangement about map GIS (below) GIS practice of Redis
Arduino框架下STM32F1/F4系列HID模式程序烧录教程
复制延迟案例(1)-最终一致性
力扣练习——45 二叉树的锯齿形层次遍历
论人生自动化
列表总结
Line generation 005
Arduino框架下ESP32重启原因串口信息输出示例
高等数学(第七版)同济大学 总习题三(后10题) 个人解答
The line chart with square PyQt5_pyqtgraph mouse
复制延迟案例(3)-单调读
C# Thread IsBackground作用
ScholarOne Manuscripts submits journal LaTeX file and cannot convert PDF successfully!
Camtasia 2022简体中文版屏幕录像和视频编辑软件
无主复制系统(2)-读写quorum
数据可视化之百变柱状图
如何解决QByteArray添加quint16双字节时错误?
“数字化重构系统,搞定 CEO 是第一步”
洛谷P2437蜜蜂路线
如果有些字段不想进行序列化怎么办?