LeetCode:求出所有存在的IP地址

Given a string containing only digits,restore it by returning all possible valid IP address
combinations.

Example 1:
Input:"25525511135"
Output:["255.255.11.135","255.255.111.35"]

解题思路:
IP每一段的数字范围是:0~255,不可以超过此范围,而且第一段不能为0,可以使用DFS进行搜索,
深度满足4时,进行返回.

GO语言实现

package main

import (
	"fmt"
	"strconv"
)

func restoreIPAddresses(s string)[]string{
	res,ip:=make([]string,0),make([]int,0)
	if len(s)<4||len(s)>12{
		res=append(res,s)
		return res
	}
	DFS(s,0,ip,&res)
	return res
}

func DFS(s string,index int,ip []int,res *[]string){
	if index==len(s){
		if len(ip)==4{
			*res=append(*res,getstring(ip))
		}
		return
	}

	if index==0{
		num,_:=strconv.Atoi(string(s[0]))
		ip=append(ip,num)
		DFS(s,index+1,ip,res)
	}else{
		num,_:=strconv.Atoi(string(s[index]))
		next:=ip[len(ip)-1]*10+num
		if next<=255&&ip[len(ip)-1]!=0{
			fmt.Println(ip)
			ip[len(ip)-1]=next
			DFS(s,index+1,ip,res)
			ip[len(ip)-1]/=10
		}
		if len(ip)<4{
			ip=append(ip,num)
			DFS(s,index+1,ip,res)
			ip=ip[:len(ip)-1]
		}
	}
}

func getstring(ip []int)string{
	res:=strconv.Itoa(ip[0])
	for i:=1;i<len(ip);i++{
		res+="."+strconv.Itoa(ip[i])
	}
	return res
}

C++语言实现

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

using namespace std;

class Solution{
private:
    vector<string> ans;
    string s;
    int  n;

public:
    vector<string> restoreIPAddress(string& _s){
        if(_s.size()<4||_s.size()>12)
            return ans;
        s=_s;
        n=_s.size();
        dfs(0,0,"");
        return ans;
    }

private:
    void dfs(int index,int depth,string path){
        if(depth==4){
            path.pop_back();
            ans.push_back(path);
            return;
        }
        int Min=max(index+1,n-(3-depth)*3);
        int Max=min(index+3,n-(3-depth));
        for(auto i=Min;i<=Max;i++){
            string split=s.substr(index,i-index);
            auto len=split.size();
            if(len>1&&split[0]=='0')
               break;
            if(stoi(split)<=255){
                dfs(i,depth+1,path+(split+'.'));
            }
        }
    }
};

int main(int argc,char* argv[]){
    string s="22522511135";
    vector<string> ans=Solution().restoreIPAddress(s);
    for(auto& i:ans)
       cout<<i<<endl; 
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

路上的追梦人

您的鼓励就是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值