Description
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
Example:
Input: “25525511135”
Output: [“255.255.11.135”, “255.255.111.35”]
Problem URL:
Solution
给一个只有数字的字符串,找到所有合法的ip地址。
Using 3 for loops to split the string into 4 substrings. Then determining all 4 substrings are valid or not. A valid IP address should have length between 1 to 3 and no more than 255. Another special case is that the substring starts with ‘0’ but its length is not 1. That is all invalid circumstance. We use a vector to contain the valid IP address and return it.
Code
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> res;
int length = s.length();
for (int i = 1; i < 4 && i < length - 2; i++){
for (int j = i + 1; j < i + 4 && j < length - 1; j++){
for (int k = j + 1; k < j + 4 && k < length; k++){
string s1 = s.substr(0, i), s2 = s.substr(i, j - i), s3 = s.substr(j, k - j), s4 = s.substr(k, length);
if (isValid(s1) && isValid(s2) && isValid(s3) && isValid(s4))
res.push_back(s1 + '.' + s2 + '.' + s3 + '.' + s4);
}
}
}
return res;
}
bool isValid(string s){
if (s.length() == 0 || s.length() > 3 || stoi(s) > 255 || (s[0] == '0' && s.length() > 1))
return false;
return true;
}
};
Time Complexity: O(n^3)
Space Complexity: O(n)
Review
C++ substr() function is substr(start pos, length).
Java subString() fuction is subString(start pos, end pos).