93. Restore IP Addresses (need DFS)

195 篇文章 0 订阅
Description

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

Example:

Input: “25525511135”
Output: [“255.255.11.135”, “255.255.111.35”]

Problem URL:

Solution

给一个只有数字的字符串,找到所有合法的ip地址。

Using 3 for loops to split the string into 4 substrings. Then determining all 4 substrings are valid or not. A valid IP address should have length between 1 to 3 and no more than 255. Another special case is that the substring starts with ‘0’ but its length is not 1. That is all invalid circumstance. We use a vector to contain the valid IP address and return it.

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

Time Complexity: O(n^3)
Space Complexity: O(n)


Review

C++ substr() function is substr(start pos, length).
Java subString() fuction is subString(start pos, end pos).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值