37复原IP地址(93)
作者:
晚于: 2020-07-29 12:00:00后提交分数乘系数50%
截止日期: 2020-08-05 12:00:00
问题描述 :
给定一个只包含数字的字符串,复原它(在中间插入点号)并返回所有可能的 IP 地址格式,输出可能的格式的数量。
有效的 IP 地址正好由四个整数(每个整数位于 0 到 255 之间)组成,整数之间用 '.' 分隔。
示例:
输入: "25525511135"
输出: 2
说明:因为可能的IP地址包括:["255.255.11.135", "255.255.111.35"]
输入说明 :
输入一个只包含数字的字符串
输出说明 :
输出一个整数
输入范例 :
输出范例 :
#include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; class Solution { public: vector<string> restoreIpAddresses(string s) { vector<string> res; if(s.size()<4) return res; vector<string> path;//存放每一个合法的序列 dfs(s,0,path,res); return res; } private: void dfs(const string &s,int pos,vector<string> &path,vector<string> &res) { int max=(4-path.size())*3;//剩余位的最大长度 ,最大12 if(s.size()-pos>max)//若剩余位数大于最大剩余位数长度,可提前终止 return ; if(path.size()==4&&pos==s.size())//path里面有四个,pos长度刚好到字符串末尾 { string str=path[0]+"."+path[1]+"."+path[2]+"."+path[3];//拼接成合法序列 res.push_back(str); return ; } for(int i=pos;i<s.size()&&i<=pos+2;i++)//从当前位置开始,长度小于总的并且最多3位 { string temp=s.substr(pos,i-pos+1); if(valid(temp))//先判断字符是否有效 { path.push_back(temp); dfs(s,i+1,path,res); path.pop_back(); } } } bool valid(string &temp) { int m=stoi(temp);//字符串转为数字 if(m>255) return false; if(temp[0]=='0'&&temp.size()>=2)//以0开头但是字符数大于2是不合法序列 return false; return true; } }; int main() { string s; cin>>s; vector<string> res=Solution().restoreIpAddresses(s); cout<<res.size(); }
posted on 2020-09-07 10:32 Hi!Superman 阅读(237) 评论(0) 编辑 收藏 举报