题解 | #数字字符串转化成IP地址#
数字字符串转化成IP地址
https://www.nowcoder.com/practice/ce73540d47374dbe85b3125f57727e1e
#include <string>
#include <vector>
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
// write code here
int n = s.size();
vector<string> ans;
string temp;
//首先利用三个for找到分割点,同时进行判断
for(int i = 1; i <= n - 3; i ++){
for(int j = i + 1; j <= n - 2; j++){
for(int k = j + 1; k <= n - 1; k++){
string ip1 = s.substr(0, i);
if(stoi(ip1) > 255 || (ip1.size() != 1 &&ip1[0] == '0')) continue;
string ip2 = s.substr(i, j - i );
if(stoi(ip2) > 255 || (ip2.size() != 1 &&ip2[0] == '0')) continue;
string ip3 = s.substr(j, k - j);
if(stoi(ip3) > 255 || (ip3.size() != 1 && ip3[0] == '0')) continue;
string ip4 = s.substr(k);
if(stoi(ip4) > 255 || (ip4.size() != 1 &&ip4[0] == '0')) continue;
temp = ip1 + '.' + ip2 + '.' + ip3 + '.' + ip4;
ans.push_back(temp);
}
}
}
return ans;
}
};
查看11道真题和解析
