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

Restore IP Addresses

时间:2014-08-22 21:15:49      阅读:277      评论:0      收藏:0      [点我收藏+]

标签:style   http   color   os   io   for   ar   div   cti   

Restore IP Addresses

 Total Accepted: 12696 Total Submissions: 61955My Submissions

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)

Have you been asked this question in an interview? 

此题是比较基础的搜索题,要找出所有的可行解,直接用DFS即可。

class Solution {
public:
    vector<string> restoreIpAddresses(string s) {
        ans.clear();
        store(s, 0, "");
        return ans;
    }
private:
    vector<string> ans;
    void store(const string& s, int b, string ip) {
        for (int i = b; i < s.size(); ++i) {
            string sub_str = s.substr(b, i - b + 1);
            if (isValidIp(sub_str)) {
                if (i + 1 == s.size() && count(ip.begin(), ip.end(), '.') == 2) {
                    ans.push_back(ip + "." + sub_str);
                } else {
                    string temp_ip = ip;
                    if (temp_ip == "") {
                        temp_ip += sub_str;
                    } else {
                        temp_ip += "." + sub_str;
                    }
                    if (count(ip.begin(), ip.end(), '.') ==3) {
                        continue;
                    }
                    store(s, i + 1, temp_ip);
                }
            }
        }
    }
    bool isValidIp(const string& s) {
        if (s.size() > 3) {
            return false;
        }
        if (s.size() == 3 && s > "255") {
            return false;
        }
        if (s.size() > 1 && s[0] == '0') {
            return false;
        }
        return true;
    }
};


Restore IP Addresses

标签:style   http   color   os   io   for   ar   div   cti   

原文地址:http://blog.csdn.net/freeliao/article/details/38761035

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