zoukankan      html  css  js  c++  java
  • [LeetCode] Restore IP Addresses

    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> res;
            int len = s.size();
            if(len<4)
                return res;
            for(int i=0;i<len-2;i++)
                for(int j=i+1;j<len-1;j++)
                    for(int k=j+1;k<len;k++){
                        if(i-0<=3 && j-i<=3 && k-j<=3){
                            
                         string sRestore =IsValidAndRestore(i,j,k,s);
                         if(sRestore != "" && find(res.begin(),res.end(),sRestore)==res.end())
                           res.push_back(sRestore);
                        }
                    
                    
                    }//end for
        return res;
        }
    private:
        
        bool valid(string s){//各子串是否合法
           istringstream is(s);
           int res;
           is>>res;
           
           if((s.size()>1 && s[0]=='0')|| res>255 || res<0)
               return false;
           else
               return true;
           
        }//end valid
        string IsValidAndRestore(int x,int y,int z,string s){
            string s1 = s.substr(0,x);
            string s2 = s.substr(x,y-x);
            string s3 = s.substr(y,z-y);
            string s4 = s.substr(z);
            string Res;
            if(valid(s1) && valid(s2) && valid(s3) && valid(s4)){
               return s1+"."+s2+"."+s3+"."+s4;
            }
            return Res;
        }//end IsValid
    };
  • 相关阅读:
    【图论】第k短路
    【图论】差分约束系统
    【图论】最短路
    【图论】Johnson算法
    HDU5878
    HDU5900
    pow的小事不简单
    math汇总
    Bellman-Ford最短路径
    图的遍历
  • 原文地址:https://www.cnblogs.com/Xylophone/p/3892774.html
Copyright © 2011-2022 走看看