[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)

最简单的情况,遍历……

class Solution {
public:
    vector<string> restoreIpAddresses(string s) {
		// Start typing your C/C++ solution below
		// DO NOT write int main() function
		vector<string> ret;
		if(s.size()>12)
			return ret;
		int length=s.size();
		for(int i=1 ; i<4 ; i++)
			for(int j=1 ; j<4 ; j++)
				for(int k=1 ; k<4 ; k++)
					for(int l=1 ; l<4 ; l++){
						if(i+j+k+l!=length)
							continue;
						string s1,s2,s3,s4;
						s1.append(s.begin(),s.begin()+i);
						s2.append(s.begin()+i,s.begin()+i+j);
						s3.append(s.begin()+i+j,s.begin()+i+j+k);
						s4.append(s.begin()+i+k+j,s.end());
						if(check(s1)&&check(s2)&&check(s3)&&check(s4)){
							string s=s1+"."+s2+"."+s3+"."+s4;
							ret.push_back(s);
						}
					}
		return ret;
	}
	bool check(const string& s){
		if(s=="")
			return false;
		int n=s.size();
        if(n>1 && s[0]=='0')
            return false;
		int num=0;
		for(int i=0 ; i<n ; i++){
			num=num*10+(s[i]-'0');
		}
		if(num>255)
			return false;
		return true;
	}
};


你可能感兴趣的:([leetcode] Restore IP Addresses)