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

[string]Restore IP Addresses

时间:2015-12-06 22:38:44      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:

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)

深度优先遍历的思想,类似的题目还有:

1.Word Search

2.Word SearchII

3.Permutations,PermutationsII

4.Letter Combinations of a Phone Number

5.Unique Paths

6.Subsets,SubsetsII

class Solution {
public:
    int strToInt(string &str)
    {
        int res = 0;
        for(int i=0;i<str.size();i++){
            res = res*10+(str[i]-0);
        }
        return res;
    }
    void dfs(string& s,int sSize,int startPos,vector<string>& res,string oneOfRes,int k)
    {
        for(int i=startPos;(i<sSize) && (i<startPos+3) ;i++){
            if(i!=startPos && s[startPos]==0){
                return;
            }
            string tmpStr = s.substr(startPos,i-startPos+1);
            int value = strToInt(tmpStr);
            if(value>255){
                return;    
            } 
            string tmpOneOfRes = oneOfRes;
            oneOfRes.empty()? oneOfRes += tmpStr : oneOfRes += "."+tmpStr;
            if(k+1<4){
                dfs(s,sSize,i+1,res,oneOfRes,k+1);
            }else{
                if(i+1==sSize){
                    if(find(res.begin(),res.end(),oneOfRes)==res.end())
                        res.push_back(oneOfRes);
                }
            }
            oneOfRes = tmpOneOfRes;
        }
    }
    vector<string> restoreIpAddresses(string s) {
        vector<string> res;
        string oneOfRes ;
        dfs(s,s.size(),0,res,oneOfRes,0);
        return res;
    }
};

 

[string]Restore IP Addresses

标签:

原文地址:http://www.cnblogs.com/zengzy/p/5024558.html

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