leetcode第一刷_Restore IP Addresses

來源:互聯網
上載者:User

字串的問題真是難,一般遞迴比較好寫代碼,一般地歸還會逾時,而且測試案例特別多。。

這道題剛拿到手時直接慌了,這情況也太多了,後來冷靜下來想想,其實還是比較單純的。一個ip地址,肯定是四個整數加三個點構成,四個整數要滿足什麼呢,0~255嘛,還有呢,就是這四個整數必須正好把原來的字串給用完。一開始忽略掉的一類測試用類是前面有0但實際這個數不是零的情況。

用什麼來窮舉呢,或者說窮舉的對象是什麼呢?當然是要插入的三個點的位置,數的有效範圍很小,因此窮舉的範圍也很小,1~3個數位而已,代碼一看,就明白是怎麼回事了。我最開始的時候想著是把每一個小數字用substr存起來,然後最後拼接,這樣的開銷太大了,不建議。

bool isValide(string s, int start, int end){    if(end - start > 3)    return false;    if(s[start] == '0' && end-start>0)    return false;    int res = 0;    for(int i=start;i<=end;i++)    res = res*10+(s[i]-'0');    if(res<0||res>255)    return false;    return true;}class Solution {public:    vector<string> restoreIpAddresses(string s) {        vector<string> res;        int len = s.length();        if(len<4)            return res;        string tp(len+3, '#');        for(int i=0;i<3&&i<len-3;i++){        if(!isValide(s, 0, i))continue;        //cout<<i<<" i"<<endl;            for(int j=i+1;j<i+4&&j<len-2;j++){            if(!isValide(s, i+1, j))continue;            //cout<<j<<" j"<<endl;                for(int k=j+1;k<j+4&&k<len-1;k++){                //cout<<k<<" k"<<endl;                if(!(isValide(s, j+1, k)&&isValide(s, k+1, len-1)))                continue;                //cout<<"**"<<endl;                int index = 0, m = 0;                while(index<=i) tp[m++] = s[index++];                tp[m++] = '.';                while(index<=j) tp[m++] = s[index++];                tp[m++] = '.';                while(index<=k) tp[m++] = s[index++];                tp[m++] = '.';                while(index<len) tp[m++] = s[index++];                //cout<<tp<<endl;                res.push_back(tp);}            }        }        return res;    }};


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.