本文主要是介绍Leetcode142: Restore IP Addresses,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given "25525511135"
,
return ["255.255.11.135", "255.255.111.35"]
. (Order does not matter)
三重循环,用三个小数点分割字符,检查每个字符对应数字合理性。
class Solution {
public:vector<string> restoreIpAddresses(string s) {vector<string> res;if(s.size()>12)return res;for(int i = 0; i < s.size(); i++){for(int j = i+1; j < s.size(); j++){for(int k = j+1; k < s.size()-1; k++){string s1 = s.substr(0, i+1);string s2 = s.substr(i+1, j-i);string s3 = s.substr(j+1, k-j);string s4 = s.substr(k+1);if(check(s1)&&check(s2)&&check(s3)&&check(s4)){string tmp = s1+"."+s2+"."+s3+"."+s4;res.push_back(tmp);}}}}return res;}bool check(string s){int value = stoi(s);if(s[0] == '0'){return s.size() == 1;}if(value<=255)return true;else return false;}
};
这篇关于Leetcode142: Restore IP Addresses的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!