2021-10-18

2021-10-18,第1张

2021-10-18 数字字符串转化成IP地址

限定语言:Kotlin、Typescript、Python、C++、Groovy、Rust、Java、Go、Scala、Javascript、Ruby、Swift、Php、Python 3

现在有一个只包含数字的字符串,将该字符串转化成IP地址的形式,返回所有可能的情况。

例如:

给出的字符串为"25525522135",

返回["255.255.22.135", "255.255.221.35"]. (顺序没有关系)

数据范围:字符串长度 

要求:空间复杂度 ,时间复杂度 

"25525522135"
输出
["255.255.22.135","255.255.221.35"]

示例2

输入
"1111"
输出
["1.1.1.1"]

示例3

输入
"000256"
输出
"[]"

注意:ip地址是由四段数字组成的数字序列,格式如 "x.x.x.x",其中 x 的范围应当是 [0,255]。

算法题解——将字符串转化为ip地址
题目描述
现在有一个只包含数字的字符串,将该字符串转化成IP地址的形式,返回所有可能的情况。
例如:
给出的字符串为"25525511135",
返回[“255.255.11.135”, “255.255.111.35”]. (顺序没有关系)

ip地址限制条件:

ip地址一共包含4段,每段用 '.'分隔
每段如果有两位及以上,则首位不能为0,如01,02
每段不能大于255
解题思路
使用深度优先搜索DFS,附加以上限制条件,并且要确保字符串都被搜索到。
代码如下:
 

class Solution {
public:
   
    vector restoreIpAddresses(string s) {
        // write code here
        if(s.size()>12 || s.empty())
            return {};    
        vector res;
        vector temp;
        dfs(s, res, temp);
        return res;
    }
    
    string convert(vector temp)
    {
        string s;
        for(int i=0;i         {
            s+=temp[i]+'.';
        }
        s+=temp[temp.size()-1];
        return s;
    }
    
    void dfs(string s,vector &res,vector &temp)
    {
        if(s.empty() && temp.size()==4)
            res.push_back(convert(temp));
        for(int n=1;n<=s.size();n++)    //这里的n不是索引,是子字符串的长度
        {
            if(s[0] == '0' && n>1)    //如果有两位及以上每段的首位不能为0
                return;
            int val = stoi(s.substr(0,n));
            if(val > 255)    //ip地址每段不能大于255
                return;
            temp.push_back(s.substr(0,n));    //符合条件插入候选数组
            dfs(s.substr(n),res,temp);     //递归搜素下一段
            temp.pop_back();    //清除temp,确保下一组ip不受影响;
        }
    }
};
 

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/3973725.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-10-21
下一篇 2022-10-21

发表评论

登录后才能评论

评论列表(0条)

保存