[LeetCode]Restore IP Addresses

本文详细介绍了两种解析IP地址的实现方法,包括深度优先搜索(DFS)和递归利用,通过验证条件来构建有效的IP地址组合。重点讨论了算法优化、边界条件判断以及如何在限制条件下生成合法的IP地址段。
class Solution {
//DFS
//Note: there are 4 special process here
public:
	void DFS(int curStep, int curPos, const string& s, string& curAns, vector<string>& ans)
	{
		if(s.size()-curPos > (5-curStep)*3)//3. cut off, for the long number
			return;
		if(curPos >= s.size()) return;//4. check if it is valid
		if(curStep == 4)
		{
			if( IsValid(curPos, s.size()-1, s) )
				ans.push_back(curAns);
		}
		for (int i = curPos; i < s.size(); ++i)
		{
			if ( IsValid(curPos, i, s) )
			{
				curAns.insert(curAns.begin()+i+curStep, '.');
				DFS(curStep+1, i+1, s, curAns, ans);
				curAns.erase(curAns.begin()+i+curStep);
			}
		}
	}
	bool IsValid( int start, int end, const string& s ) 
	{
		if(s[start] == '0' && end != start)//1. 001 is not valid
			return false;
		if(end-start > 3)//2. len greater than 3 is also not valid, too long may cause overflow
			return false;
		int res = 0;
		for (int i = start; i <= end; ++i)
			res = res*10+s[i]-'0';
		if(res <= 255)
			return true;
	}
	vector<string> restoreIpAddresses(string s) {
		// Start typing your C/C++ solution below
		// DO NOT write int main() function
		vector<string> ans;
		string curAns = s;
		DFS(1, 0, s, curAns, ans);
		return ans;
	}

};

second time

class Solution {
//1. terminate case should satisfy all the conditions
//2. cut off should at leat cover the out of range case
//3. move should satisfy all the necessary conditions
public:
    void restoreUtil(string& s, int curIdx, vector<int>& curPath, vector<string>& allPath)
    {
        if(curPath.size() == 4 && curIdx == s.size())
        {
            string tmp = s;
            for(int i = curPath.size()-2; i >= 0; --i) tmp.insert(curPath[i]+1, 1, '.');//insert char before pos
            allPath.push_back(tmp);
            return;
        }
        if(curPath.size() >= 4 || curIdx >= s.size()) return;
        
        int curNum = s[curIdx]-'0';
        int end = curIdx;
        do
        {
            curPath.push_back(end);
            restoreUtil(s, end+1, curPath, allPath);
            curPath.pop_back();
            end++;
            curNum = curNum*10+s[end]-'0';
        }while(end < s.size() && curNum <= 255 && s[curIdx] != '0');
    }
    vector<string> restoreIpAddresses(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<int> curPath;
        vector<string> allPath;
        restoreUtil(s, 0, curPath, allPath);
        return allPath;
    }
};


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

AI记忆

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值