426. Restore IP Addresses

Code(Language:C++) (Judger:cloudjudge-cluster-5)
class Solution {
public:
    /**
     * @param s: the IP string
     * @return: All possible valid IP addresses
     */
    vector<string> restoreIpAddresses(string &s) {
        // write your code here
        vector<string> res; 
        const int size = s.size();
        if(size < 4 || size > 12){
            return res; 
        }
        vector<string> resElem;
        dfs(s, res, resElem, 0); 
        return res; 
    }
    void dfs(string &s, vector<string> &res, vector<string> &resElem, int start){
        int size = s.size(); 
        if(start == s.size()){
           if(resElem.size() == 4){
               res.push_back(resElem[0] + "." + resElem[1] + "." + resElem[2] + "." + resElem[3]); 
           }
           return; 
        }
        if(resElem.size() > 4){
            return; 
        }
        for(int i = start; i < min(start + 3, size); i++){
            if(s[start] == '0' && i > start){
                continue; 
            }
            string sub = s.substr(start, i - start + 1);
            if(stoi(sub) > 255){
                continue; 
            }//不能这么玩 string直接比!!! “4” 比 "255"大啊啊!!要转换成 int后再比啊啊啊
            resElem.push_back(sub);
            dfs(s, res, resElem, i + 1); 
            resElem.pop_back(); 
        }
        return; 
    }
};

Comments

Popular posts from this blog

1427. Split Array into Fibonacci Sequence

Amazon OA 763. Partition Labels

05/25 周一