LeetCode-93-复原IP地址 发表于 2020-03-13 | 分类于 LeetCode | 评论数: | 热度: ℃ 本文字数: 4.2k | 阅读时长 ≈ 4 分钟 给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。 示例: 12输入: "25525511135"输出: ["255.255.11.135", "255.255.111.35"] Code12345678910111213141516171819202122232425262728293031323334353637class Solution {public: vector<string> res; vector<string> restoreIpAddresses(string s) { //预处理,长度为12,只有一种结果,直接返回 if(s.length()==12){ for (int j = 0;j <4;j+=3) { string str = s.substr(j, 3); if (str[0] == '0' || stoi(str) > 255) return res; } for(int i=3;i<=11;i+=4) s.insert(i,"."); res.push_back(s); return res; } //递归dfs处理字符串 dfs(s,"",0,0); return res; } void dfs(string s,string temp,int index,int count){ //记录递归的层数 if(count>4)return; if(count==4&&index==s.length()) res.push_back(temp); for(int i=1;i<4;i++){ if(index+i>s.length())return; string str = s.substr(index,i); //stoi(str)将字符串转为数字 if((str.length()>1&&str[0]=='0')||stoi(str)>255) return; dfs(s,temp+str+(count==3?"":"."),index+i,count+1); } }}; 相关文章推荐 LeetCode-130-被围绕的区域 LeetCode-131-分割回文串 LeetCode-200-岛屿数量 LeetCode-216-组合总和III LeetCode-40-组合总和II ----\(˙<>˙)/----赞赏一下吧~ 打赏 微信支付 支付宝 本文作者: wicherQAQ 本文链接: https://wicherqaq.github.io/2020/03/13/LeetCode-93-%E5%A4%8D%E5%8E%9FIP%E5%9C%B0%E5%9D%80/ 版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!