It is really difficult to solve the string problem. Generally, recursion is better to write code. Generally, return times out, and there are many test cases ..
When I got my hand on this question, I was panic. There were too many cases. Then I calmed down and thought about it. In fact, it was quite simple. An IP address must be composed of four integers and three vertices. What should the four integers satisfy? 0 ~ 255. What's more, the four integers must just run out of the original string. The first class of test class ignored at the beginning is the case where there is 0 but the actual number is not zero.
What is the purpose of the promotion, or what is the object of the promotion? Of course, it is the position of the three points to be inserted. The valid range of the number is small, so the range of the exhaustive operation is also small, 1 ~ Three digits. Once the code is viewed, you can see what is going on. I first thought about saving every small number with substr, and then splicing it. This overhead is too large and is not recommended.
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; }};