首页 > 代码库 > Leetcode: Restore IP Addresses
Leetcode: 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> result; vector<string> ip; if(s.length() < 4 || s.length() > 12) return result; dfs(result, ip, s, 1); return result; } void dfs(vector<string> & result, vector<string> &ip, string s, int level){ if(level == 4){ if(s.length() > 3 || s[0] == ‘0‘&& s.length() != 1) return; if(atoi(s.c_str()) >255) return; ip.push_back(s); string tmp; for(auto i = ip.begin(); i != ip.end(); i++) tmp += *i + "."; tmp.pop_back(); result.push_back(tmp); ip.pop_back(); }else{ if(s[0] == ‘0‘){ ip.push_back("0"); if(s.length() > 1)dfs(result, ip, s.substr(1), level+1); ip.pop_back(); }else{ for(int i = 1; i <=3 && i < s.length(); i++){ string tmp = s.substr(0,i); if(atoi(tmp.c_str()) <= 255){ ip.push_back(tmp); dfs(result, ip, s.substr(i), level+1); ip.pop_back(); } } } } }};
Leetcode: Restore IP Addresses
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。