LEETCODE,LeetCode93. 復原IP地址

 2023-10-08 阅读 36 评论 0

摘要:93. 復原IP地址 給定一個只包含數字的字符串,復原它并返回所有可能的 IP 地址格式。 LEETCODE、輸入"010010" 輸出["0.10.0.10","0.100.1.0"] 思路 ①字符串長度為[4,12]符合條件,然后將小數點遍歷,找出p1,p2,p3,p4的值[0,255]符

93. 復原IP地址

給定一個只包含數字的字符串,復原它并返回所有可能的 IP 地址格式。

LEETCODE、輸入"010010"

輸出["0.10.0.10","0.100.1.0"]

思路

①字符串長度為[4,12]符合條件,然后將小數點遍歷,找出p1,p2,p3,p4的值[0,255]符合條件,p1舉例:當開頭的字符串是0的時候,字符串長度只能為0.當p1長度大于3則返回false(>255)。

class Solution {
private:bool judge(string s, int a, int b, int c, int d, int len){if(b-a>3 || c-b>3 || d-c>3 || len-d>3) return false;if((s[a]=='0' && b-a!=1) ||(s[b]=='0' && c-b!=1) ||(s[c]=='0' && d-c!=1) ||(s[d]=='0' && len-d!=1)) return false;int p1=0,p2=0,p3=0,p4=0;p1 = atoi(s.substr(a,b-a).c_str());p2 = atoi(s.substr(b,c-b).c_str());p3 = atoi(s.substr(c,d-c).c_str());p4 = atoi(s.substr(d,len-d).c_str());if(p1>255 || p2>255 || p3>255 ||p4>255) return false;string one = to_string(p1)+'.'+to_string(p2)+'.'+to_string(p3)+'.'+to_string(p4);bool flag=false;for(int i=0;i<res.size();i++){if(res[i]==one){flag=true;break;}}if(!flag)res.push_back(one);return true;}
public:vector<string> res;vector<string> restoreIpAddresses(string s) {res.clear();//清空int len = s.length();if(len>12 || len<4) return res;for(int b=1;b<len;b++){for(int c=b+1;c<len;c++){for(int d=c+1;d<len;d++){judge(s,0,b,c,d,len);}}}return res;}
};

?

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/2/133621.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息