Saturday, April 19, 2014

[LeetCode] Restore IP Address

Problem Statement (link):
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)
Analysis:
There's no specific algorithm used in this problem. I loop through all the possible positions to add dots.

A value IP address is defined such that each three-digits segment is valued between 0 and 255, inclusive. A corner case is that each segment should begin with non-zero digits, i.e., xx.013.xxx.xxx is not a valid segmentation as 013 is invalid.

Code:
class Solution {
public:
    vector<string> restoreIpAddresses(string s) {
        vector<string> out;
        if (s.size()<4 || s.size()>12) return out;
        // loop thru all possible positions for adding "."
        for (int i=0; i<s.size()-3; i++) {
            for (int j=i+1; j<s.size()-2; j++) {
                for (int k=j+1; k<s.size()-1; k++) {
                    int a=atoi(s.substr(0,i+1).c_str());
                    string t=to_string(a);
                    if (t!=s.substr(0,i+1)) continue; // to eliminate case where starts with 0
                    int b=atoi(s.substr(i+1,j-i).c_str());                     t=to_string(b);                     if (t!=s.substr(i+1,j-i)) continue;
                    int c=atoi(s.substr(j+1,k-j).c_str());                     t=to_string(c);                     if (t!=s.substr(j+1,k-j)) continue;
                    int d=atoi(s.substr(k+1,s.size()-k).c_str());                     t=to_string(d);                     if (t!=s.substr(k+1,s.size()-k)) continue;
                    if (a<=255 && b<=255 && c<=255 && d<=255)                         out.push_back(s.substr(0,i+1)+"."+s.substr(i+1,j-i)+"."+s.substr(j+1,k-j)+"."+s.substr(k+1,s.size()-k));                 }             }         }         return out;     } };

No comments:

Post a Comment