[LintCode] Restore IP Address 复原IP地址
2016-07-19 23:48
369 查看
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
Have you met this question in a real interview?
Yes
Example
Given
Order does not matter.
LeetCode上的原题,请参见我之前的博客Restore IP Addresses。
解法一:
解法二:
Have you met this question in a real interview?
Yes
Example
Given
"25525511135", return
[ "255.255.11.135", "255.255.111.35" ]
Order does not matter.
LeetCode上的原题,请参见我之前的博客Restore IP Addresses。
解法一:
class Solution { public: /** * @param s the IP string * @return All possible valid IP addresses */ vector<string> restoreIpAddresses(string& s) { vector<string> res; helper(s, 4, "", res); return res; } void helper(string s, int k, string out, vector<string>& res) { if (k == 0) { if (s.empty()) res.push_back(out); return; } for (int i = 1; i < 4; ++i) { if (s.size() < i) break; int val = stoi(s.substr(0, i)); if (val > 255 || i != to_string(val).size()) continue; helper(s.substr(i), k - 1, out + s.substr(0, i) + (k == 1 ? "" : "."), res); } } };
解法二:
class Solution { public: /** * @param s the IP string * @return All possible valid IP addresses */ vector<string> restoreIpAddresses(string& s) { vector<string> res; for (int a = 1; a < 4; ++a) for (int b = 1; b < 4; ++b) for (int c = 1; c < 4; ++c) for (int d = 1; d < 4; ++d) if (a + b + c + d == s.size()) { int A = stoi(s.substr(0, a)); int B = stoi(s.substr(a, b)); int C = stoi(s.substr(a + b, c)); int D = stoi(s.substr(a + b + c, d)); if (A <= 255 && B <= 255 && C <= 255 && D <= 255) { string t = to_string(A) + "." + to_string(B) + "." + to_string(C) + "." + to_string(D); if (t.size() == s.size() + 3) res.push_back(t); } } return res; } };
相关文章推荐
- 关于上一篇鼠标移到按钮时的“按下”效果的三种方法
- 树的定义与基本术语
- 笔记:正则表达式
- Flask Web开发 第2章
- 有关dependencies和dependencyManagement简单介绍
- 【设计模式】Command模式
- UE4类修饰符
- 从事技术开发以来的一些个人经验
- 292. Nim Game
- MySQL 查询之分页优化
- 线性表顺序实现和链式实现区别
- PHP开发网站第二步:关联并配置PHP与Apache2.4
- UE4类修饰符
- iOS开发拓展篇—音乐的播放
- Windows平台下编译OpenCV扩展的opencv_contrib
- 带随机种子的javascript随机函数
- java web项目测试实现银联支付
- 配置基于Devstack的嵌套KVM虚拟化
- 说说React的事(一)
- 主流光照模型简介(1)——Lambert模型