leetcode93 复原IP地址 回溯

python

'''

Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, OCaml, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.

'''
from typing import List


class Solution:
    def restoreIpAddresses(self, s: str) -> List[str]:
        size = len(s)
        if size < 4 or size > 12:
            return []

        path = []
        res = []
        self.__dfs(s, size, 0, 0, path, res)
        return res

    def __dfs(self, s, size, split_times, begin, path, res):
        if begin == size:
            if split_times == 4:
                res.append('.'.join(path))
            return

        if size - begin < (4 - split_times) or size - begin > 3 * (4 - split_times):
            return

        for i in range(3):
            if begin + i >= size:
                break

            ip_segment = self.__judge_if_ip_segment(s, begin, begin + i)

            if ip_segment != -1:
                path.append(str(ip_segment))
                self.__dfs(s, size, split_times + 1, begin + i + 1, path, res)
                path.pop()

    def __judge_if_ip_segment(self, s, left, right):
        size = right - left + 1

        if size > 1 and s[left] == '0':
            return -1

        res = int(s[left:right + 1])

        if res > 255:
            return - 1
        return res

mysolo = Solution()
res = mysolo.restoreIpAddresses("25525511135")
print(res)

作者:liweiwei1419
链接:https://leetcode.cn/problems/restore-ip-addresses/solution/hui-su-suan-fa-hua-tu-fen-xi-jian-zhi-tiao-jian-by/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

C++

  • 使用 int ip = stoi(s);转换数值
#include <iostream>
#include <queue>
#include <vector>
#include<memory>
using namespace std;


class Solution
{
private:
    vector<string> result;
public:
    vector<string> restoreIpAddresses(string s)
    {
        vector<string> path;
        
        if(s.size()<4||s.size()>16)//如果string是非法的ip字符串则直接返回即可
            return result;

        dfs(s, 0, path);
        return result;
    }
    bool __judge_if_ip_segment(string s) //判断是否是一个合法的IP范围
    {
        if(s[0]=='0'&&s.size()>=2)  //不能有前置0
            return false;
        cout<<s<<endl;
        int ip = stoi(s);//stoi函数. 作用是将 n 进制的字符串转化为十进制
        if(ip>255) //不能超出范围
            return false;
        return true;
    }
    //pos表示当前的起始位置,path表示当前已存路径
    void dfs(string &s,int pos,vector<string> &path)
    {
        if(path.size()==4)
        {
            if(pos==s.size()){//满足条件,存储结果
                string s = "";
                for (int i = 0; i < 3;i++)
                    s = s + path[i] + '.';
                s += path[3];
                result.push_back(s);
                return;
            }else{
                // //如果没有遍历至结尾说明该部分是无效的
                // if(path.size()==4&&pos<s.size())
                // if(path.size()==4&&pos>s.size())
                return;
            }
        }

       
        for (int i = 0; i <= 2;i++)
        {
            if(pos<s.size()){//如果前两个就用完了所有数据,那么就停止
                string ip = s.substr(pos, i + 1); //截取
                if(!__judge_if_ip_segment(ip)) 
                    break; 
                path.push_back(ip);
                dfs(s, pos+i + 1, path);
                path.pop_back();
            }
        }
    }
};


int main()
{
    unique_ptr<Solution> mysolo = unique_ptr<Solution>(new Solution());
    cout<<"Hello World"<<endl;
    string s = "101023"; //"0000";// "25525511135"; //
    vector<string> res = mysolo->restoreIpAddresses(s);
    for(auto v: res){
        cout<<v<<"-->";
    }
    return 0;
}

cg

  • stoi string to int

  • int num = 123456789;
    string s = to_string(num);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值