码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: Restore IP Addresses

时间:2014-12-02 22:12:13      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   os   sp   for   on   div   

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) {
        vector<string> result;
        vector<string> ip;
        if(s.length() < 4 || s.length() > 12) return result;
        dfs(result, ip, s, 1);
        return result;
    }
    void dfs(vector<string> & result, vector<string> &ip, string s, int level){
        if(level == 4){
            if(s.length() > 3 || s[0] == 0&& s.length() != 1) return;
            if(atoi(s.c_str()) >255) return;
            ip.push_back(s);
            string tmp;
            for(auto i = ip.begin(); i != ip.end(); i++)
                tmp += *i + ".";
            tmp.pop_back();
            result.push_back(tmp);
            ip.pop_back();
        }else{
            if(s[0] == 0){
                ip.push_back("0");
                if(s.length() > 1)dfs(result, ip, s.substr(1), level+1);
                ip.pop_back();
            }else{
                for(int i = 1; i <=3 && i < s.length(); i++){
                    string tmp = s.substr(0,i);
                    if(atoi(tmp.c_str()) <= 255){
                        ip.push_back(tmp);
                        dfs(result, ip, s.substr(i), level+1);
                        ip.pop_back();
                    }
                }
            }
        }
    }
};

 

Leetcode: Restore IP Addresses

标签:style   blog   io   color   os   sp   for   on   div   

原文地址:http://www.cnblogs.com/Kai-Xing/p/4138595.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!