Restore IP Addresses(leetcode)

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)

这道题用可以用三个iterator分割成四个字符串,然后对每个字符串分析是否合法即可。

需要注意的一点是1.00.1.1这类IP是否合法,(OJ)上认为这类以零开头的非零数值全部是非法值。但是实际上我认为应该还是算合法的IP地址吧。

class Solution {
public:
    vector<string> restoreIpAddresses(string s) {
        vector<string> vec;
        if( s.size() > 12 )     return vec;
        for( string::iterator i = s.begin() + 1;i < s.end();++i )   {
            for( string::iterator j = i + 1;j < s.end();++j )
                for( string::iterator k = j + 1;k < s.end();++k )  {
                    string str1(s.begin(),i),str2(i,j),str3(j,k),str4(k,s.end());
                    if( ispos(str1) && ispos(str2) && ispos(str3) && ispos(str4) )    {
                        string str = str1 + '.' + str2 + '.' + str3 + '.' + str4;
                        vec.push_back(str);
                    }
                }
        }
		return vec;
    }
    bool ispos( string str )    {
        int sum = 0;
        for( string::iterator it = str.begin();it != str.end();++it )   {
            sum = sum * 10 + *it - '0';
        }
		if( str[0] == '0')  {
		    if( str.size() == 1 )
		        return true;
		    return false;
		}
		else    {
		    if( sum >= 0 && sum < 256 )
		        return true;
		    return false;
		}
    }
};


猜你喜欢

转载自blog.csdn.net/u013434984/article/details/32163029