• Leetcode: Restore IP Addresses


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

    For example:
    Given "25525511135",

    return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)

    好多特殊情况:

    递归到最后一个数是9245587303,stoi越界

    多个零:10.000.0.1

    数字前面是以0开始:10.010.0.1

    vector<string> restore(string s, int n, bool &flag)
    	{
    		vector<string> res;
    		if(s.length() < n) {flag = false; return res;}
    		if(n==1)
    		{
    			if(s.length()>3){flag=false;return res;}//maybe larger than int
    			int ip = stoi(s);
    			if(ip==0 && s.length() >1) flag = false;
    			else if(ip>0 && s[0] == '0') flag = false;
    			else if((ip >= 0) && (ip < 256))
    			{
    				res.push_back(s);
    				flag = true;
    			}else
    				flag = false;
    			return res;
    		}
    		int loop = s.length() - n +1;//garuntee every ip address is no less than one bit
    		loop = min(loop,3);
    		for(int i = 1; i <= loop; i++)
    		{
    			string ipstr = s.substr(0,i);
    			int ip = stoi(ipstr);
    			if(ip==0 && ipstr.length() >1)break;
    			if(ip>0 && ipstr[0] == '0')break;
    			if((ip>=0) && (ip < 256))
    			{
    				string suffix = s.substr(i);
    				bool f = false;
    				vector<string> tmp = restore(suffix,n-1,f);
    				if(f)
    				{
    					flag = true;
    					for(int k = 0; k < tmp.size(); k++)
    						res.push_back(ipstr + '.' + tmp[k]);
    				}
    			}
    		}
    		return res;
    	}
    	vector<string> restoreIpAddresses(string s) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
    		vector<string> res;
    		bool flag = false;
    		res = restore(s,4,flag);
    		return res;
        }


  • 相关阅读:
    array与xml转换实现(转)
    设计模式之: 策略模式
    设计模式之: 代理模式
    设计模式之: 状态模式
    dedecms分页
    dedecms导出csv文件
    假如项目中使用到了多 表查询,怎么办?
    git忽略某个文件夹
    git忽略某个文件
    无极限分类
  • 原文地址:https://www.cnblogs.com/riskyer/p/3354330.html
Copyright © 2020-2023  润新知