题解 | #数字字符串转化成IP地址#
数字字符串转化成IP地址
https://www.nowcoder.com/practice/ce73540d47374dbe85b3125f57727e1e
#include <unistd.h>
class Solution {
public:
/**
*
* @param s string字符串
* @return string字符串vector
*/
vector<string> restoreIpAddresses(string s) {
// write code here
int n =s.length();
vector<string> result;
for(int i = 1;i<4&&i<n-2;i++)
{ for(int j = i+1;j < i + 4&&j<n-1;j++)
{ for(int k = j+1;k < j+4 &&k<n; k++ )
{
if(n-k>=4)
continue;
string a = s.substr(0,i);
string b = s.substr(i,j-i);
string c = s.substr(j,k-j);
string d = s.substr(k);
if(stoi(a)>255||stoi(b)>255||stoi(c)>255||stoi(d)>255)
continue;
if((a.length()!=1&&a[0]=='0')||(b.length()!=1&&b[0]=='0')||(c.length()!=1&&c[0]=='0')||(d.length()!=1&&d[0]=='0'))
{
continue;
}
string tem = a+"."+b+"."+c+"."+d;
result.push_back(tem);
}
}
}
return result;
}
};
这题真的很变态……
