玩命加载中 . . .

复原IP地址


描述

有效 IP 地址 正好由四个整数(每个整数位于 0 到 255 之间组成,且不能含有前导 0),整数之间用 ‘.’ 分隔。

例如:”0.1.2.201” 和 “192.168.1.1” 是 有效 IP 地址,但是 “0.011.255.245”、”192.168.1.312” 和 “192.168@1.1“ 是 无效 IP 地址。
给定一个只包含数字的字符串 s ,用以表示一个 IP 地址,返回所有可能的有效 IP 地址,这些地址可以通过在 s 中插入 ‘.’ 来形成。你 不能 重新排序或删除 s 中的任何数字。你可以按 任何 顺序返回答案。

示例 1:

输入:s = “25525511135”
输出:[“255.255.11.135”,”255.255.111.35”]
示例 2:

输入:s = “0000”
输出:[“0.0.0.0”]
示例 3:

输入:s = “101023”
输出:[“1.0.10.23”,”1.0.102.3”,”10.1.0.23”,”10.10.2.3”,”101.0.2.3”]

提示:

1 <= s.length <= 20
s 仅由数字组成

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/restore-ip-addresses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

C++代码

#include <iostream>
#include <vector>
#include <string>

using namespace std;

class Solution {
public:
    vector<string> restoreIpAddresses(string s) {
        vector<string> res;
        vector<string> path;
        dfs(s, 0, path, res);
        return res;
    }

    void dfs(string s, int start, vector<string>& path, vector<string>& res) {
        // 如果已经找到了四个合法的IP地址段,且整个字符串被遍历完了,就将路径加入结果中
        if (start == s.size() && path.size() == 4) {
            string ip = path[0] + "." + path[1] + "." + path[2] + "." + path[3];
            res.push_back(ip);
            return;
        }

        // 如果还没有找到四个合法的IP地址段,就继续寻找
        if (path.size() < 4) {
            for (int i = start; i < start + 3 && i < s.size(); i++) {
                string sub = s.substr(start, i - start + 1);
                if (is_valid(sub)) {
                    path.push_back(sub);
                    dfs(s, i + 1, path, res);
                    path.pop_back();
                }
            }
        }
    }

    bool is_valid(string s) {
        // 判断当前子串是否合法
        if (s.size() > 1 && s[0] == '0') {
            return false;
        }
        int num = stoi(s);
        return num >= 0 && num <= 255;
    }
};

int main() {
    Solution s;
    vector<string> res = s.restoreIpAddresses("25525511135");
    for (auto str : res) {
        cout << str << endl;
    }
    return 0;
}

Python代码

class Solution:
    def restoreIpAddresses(self, s: str) -> List[str]:
        res = []
        path = []
        self.dfs(s, 0, path, res)
        return res

    def dfs(self, s, start, path, res):
        # 如果已经找到了四个合法的IP地址段,且整个字符串被遍历完了,就将路径加入结果中
        if start == len(s) and len(path) == 4:
            res.append(".".join(path))
            return

        # 如果还没有找到四个合法的IP地址段,就继续寻找
        if len(path) < 4:
            for i in range(start, start + 3):
                # 判断当前子串是否合法
                if i < len(s) and self.is_valid(s[start:i+1]):
                    path.append(s[start:i+1])
                    self.dfs(s, i+1, path, res)
                    path.pop()

    def is_valid(self, s):
        # 判断当前子串是否合法
        if len(s) > 1 and s[0] == '0':
            return False
        num = int(s)
        return num >= 0 and num <= 255

文章作者: Jack Tim
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Jack Tim !
评论
  目录