• LeetCode Restore IP Addresses


    DFS

    class Solution {
    public:
    	vector<string> restoreIpAddresses(string s)
    	{
    		return insertDot(s, 0, 3);
    	}
    	
    	vector<string> insertDot(string s, int beginIndex, int countOfDot /*3, 2, 1, 0*/)
    	{
    		vector<string> result;
    		if( (s.size() - beginIndex) < (countOfDot + 1) || (s.size() - beginIndex - 1) > (countOfDot +1) * 3)
    			return result;
    		
    		if(countOfDot == 0)
    		{
    			string partition = s.substr(beginIndex);
    			if(partition.size() > 1 && partition[0] == '0') //Error 4: if the first char is 0, then no more chars, such as 1.00.1.1 is no valid;
    			{
    				return result;
    			}
    			int val = std::stoi(partition);
    			if(val >= 0 && val <256)
    			{
    				result.push_back(partition);
    			}
    			return result;
    		}
    		
    		for(int i = beginIndex + 1; i< s.size();i++ ) //Error 1: i< s.size() -1
    		{
    			string partition = s.substr(beginIndex, i - beginIndex);
    			if(partition.size() > 1 && partition[0] == '0') //Error 3: if the first char is 0, then no more chars, such as 1.00.1.1 is no valid;
    			{
    				break;
    			}
    			int val = std::stoi(partition);
    			if(val > 255)
    				break;
    			if(val >= 0 && val <256)
    			{
    				vector<string> subresult = insertDot(s, i, countOfDot - 1);
    				if(subresult.size() != 0)
    				{
    					for(int j = 0; j< subresult.size(); j++) //Error 2: j< s.size() -1
    					{
    						string onepartition = partition + "." + subresult[j];
    						result.push_back(onepartition);
    					}
    				}
    			}
    		}
    		return result;
    	}
    };
    
  • 相关阅读:
    ANGULAR 开发用户选择器指令
    ANGULARJS 动态编译添加到dom中
    poj1061
    poj1077
    poj1095
    poj1102
    poj1088
    血痹汤治四肢麻木
    重用白术、苡仁治腰痛
    腰间盘突出方(刘力红)
  • 原文地址:https://www.cnblogs.com/whyandinside/p/5281924.html
Copyright © 2020-2023  润新知