zoukankan      html  css  js  c++  java
  • resotreIpAddress

    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)

    Subscribe to see which companies asked this question

     1 #include <string>
     2 #include <vector>
     3 using namespace std;
     4 class Solution {
     5 public:
     6     vector<string> restoreIpAddresses(string s) {  
     7         vector<string> result;
     8         vector<int> path;
     9         dfs(s,0,0,path,result);
    10         return result;
    11     }
    12 private:
    13     void dfs(string& s,int start,int num,
    14         vector<int>& path,vector<string>& result){
    15         if(num == 3) {
    16             string str = s;
    17             for(int i=0;i<3;i++){    
    18                 str.insert(path[i]+i,1,'.');
    19             }
    20             result.push_back(str);
    21             return;
    22         }
    23 
    24         for(int i=1;i<4;i++){
    25             if((start+i)<s.length() && 3-num<=s.substr(start+i).length() && s.substr(start+i).length()<=(3-num)*3){
    26                 if(stoi(s.substr(start,i))<=255){
    27                     if(i>1 && s[start] =='0') break;
    28                     if(num==2 && stoi(s.substr(start+i))>255) continue;
    29                     if(num==2 && s.substr(start+i).length()>1 && s[start+i]=='0') continue;
    30 
    31                     if(path.empty()) path.push_back(i);
    32                     else path.push_back(path.back()+i);
    33                      dfs(s,start+i,num+1,path,result);
    34                      path.pop_back();
    35                 }
    36             }
    37         }
    38     }
    39 };
    40 int main(){
    41     string IPaddress="1203045";
    42     Solution s;
    43     vector<string> result;
    44     result = s.restoreIpAddresses(IPaddress);
    45     return 0;
    46 }
  • 相关阅读:
    小写数字转化为大写工具类
    java中关于日期类Calendar的简单使用
    ArrayList用法总结
    滚动条(附:定时调用)
    百度Echarts的使用总结
    Datatables 使用总结
    字符串(String、StringBuffer、StringBuilder)
    sqlserver 脚本方式导出数据到excel
    前端面试
    数据库面试
  • 原文地址:https://www.cnblogs.com/wxquare/p/4997239.html
Copyright © 2011-2022 走看看