题解 | #数字字符串转化成IP地址#

数字字符串转化成IP地址

https://www.nowcoder.com/practice/ce73540d47374dbe85b3125f57727e1e

#include <unistd.h>
class Solution {
public:
    /**
     * 
     * @param s string字符串 
     * @return string字符串vector
     */
    vector<string> restoreIpAddresses(string s) {
        // write code here
        int n =s.length();
        vector<string> result;
        for(int i = 1;i<4&&i<n-2;i++)
        {   for(int j = i+1;j < i + 4&&j<n-1;j++)
            { for(int k = j+1;k < j+4 &&k<n; k++ )
              {
                    if(n-k>=4) 
                        continue; 
                    string a = s.substr(0,i);
                    string b = s.substr(i,j-i);
                    string c = s.substr(j,k-j);
                    string d = s.substr(k);
                    if(stoi(a)>255||stoi(b)>255||stoi(c)>255||stoi(d)>255)
                        continue;
                    if((a.length()!=1&&a[0]=='0')||(b.length()!=1&&b[0]=='0')||(c.length()!=1&&c[0]=='0')||(d.length()!=1&&d[0]=='0'))
                    {
                        continue;
                    }
                    string tem = a+"."+b+"."+c+"."+d;
                    result.push_back(tem);
              }
            }
        }
        return result; 
    }
};

这题真的很变态……

全部评论

相关推荐

05-01 22:41
中南大学 Java
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
05-01 13:13
ecece:这么明目张胆虚报就业率啊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务