자연수로만 이루어진 문자열 s를 받는다.
이 문자열에서 유효한 IP 주소가 될 수 있는 것들을 추려내서 반환해야 한다.
유효한 IP 주소의 조건은 아래와 같다
A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros. - For example, "0.1.2.201" and "192.168.1.1" are valid IP addresses, but "0.011.255.245", "192.168.1.312" and "192.168@1.1" are invalid IP addresses.
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> result{};
string temp{};
_length = s.size();
SearchDFS(0, s, result);
return result;
}
private:
vector<string> _ip{};
int _length{};
void SearchDFS(int index, string& s, vector<string> &result)
{
if (_ip.size() == 4)
{
if (index == _length)
{
string temp{_ip[0] + '.' + _ip[1] + '.' + _ip[2] + '.' + _ip[3]};
result.push_back(std::move(temp));
}
return;
}
for (int i = 1; i <= 3 && index + i <= _length; i++)
{
string temp = s.substr(index, i);
if (255 < stoi(temp))
{
continue;
}
_ip.push_back(temp);
SearchDFS(index + i, s, result);
_ip.pop_back();
if (temp == "0")
{
break;
}
}
return;
}
};