leetcode_102 Restore IP Addresses

161 篇文章 0 订阅

题目:

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

A valid IP address consists of exactly four integers (each integer is between 0 and 255) separated by single points.

Example:

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

使用不同的分割方法列举所有可能情况,判断分割是否有效,若有效则记录

代码如下:

class Solution {
public:
    bool isVaildIP(string s)
    {
        if(s.length() > 3 || s.length() == 0 || (s.length() > 1 && s[0] == '0') || atoi(s.c_str()) > 255 )
        {
            return false;
        }
        return true;
    }
    vector<string> restoreIpAddresses(string s) {
        int len = s.length();
        vector<string> res;
        for(int i = 1; i < 4 && i < len - 2; i++)
        {
            for(int j = i + 1; j < i + 4 && j < len - 1; j++)
            {
                for(int k = j + 1; k < j + 4 && k < len; k++)
                {
                    string s1 = s.substr(0,i);
                    string s2 = s.substr(i,j-i);
                    string s3 = s.substr(j,k-j);
                    string s4 = s.substr(k,len-k);
                    if(isVaildIP(s1) && isVaildIP(s2) && isVaildIP(s3) && isVaildIP(s4))
                    {
                        res.push_back(s1 + "." + s2 + "." + s3 + "." + s4);
                    }
                }
            }
        }
        return res;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值