LeetCode/solutions/93. Restore IP Addresses.md
2019-04-02 22:04:37 +08:00

40 lines
1.9 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [93. Restore IP Addresses](https://leetcode.com/problems/restore-ip-addresses/)
# 思路
题目要求将一个全数字的字符串转换成所有可能的IP地址串。我们知道IP地址由32位二进制数组成为便于使用我们常将IP地址分成四段每段八位这样每段的十进制范围就是0-255另外要排除前导0如"01"这种情况,所以我们
可以先写一个判断一个字符串是否是合法IP一段的函数。
然后再将字符串进行分段,在输入字符串中插入三个点就可以将字符串分为四段。因为要求出所有情况,所以考虑用递归。
我们用k来表示当前还需要分的段数如果k = 0则表示三个点已经加入完成四段已经形成若这时剩余字符串刚好为空则将当前分好的结果保存。
若k != 0, 则对于剩下的字符串,我们分别用一位,两位,三位来尝试对其分割,分别判断其合不合法,如果合法,则调用递归继续分剩下的字符串,最终和求出所有合法组合。
# C++
``` C++
class Solution {
private:
bool isValid(string s) {
if (s.empty() || s.size() > 3 || (s.size() > 1 && s[0] == '0')) return false;
int res = atoi(s.c_str());
return res <= 255 && res >= 0;
}
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 <= 3; ++i) { // 子串长度只可能是1、2或3
if (s.size() >= i && isValid(s.substr(0, i))) {
string tmp = out + s.substr(0, i);
if (k > 1) tmp += ".";
helper(s.substr(i), k - 1, tmp, res);
}
}
}
public:
vector<string> restoreIpAddresses(string s) {
vector<string> res;
helper(s, 4, "", res);
return res;
}
};
```