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

数字字符串转化成IP地址

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

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @return string字符串vector
     */
    vector<string> restoreIpAddresses(string s) {
        // write code here
        vector<string> res;
        int n = s.length();

        for(int i = 1; i < 4 && i < n - 2; ++i){
            for(int j = i + 1; j < i + 4; ++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 tmp = a + "." + b + "." + c + "." + d;
                    res.push_back(tmp);
                }
            }
        }
        return res;
    }
};

全部评论

相关推荐

迷茫的大四🐶:价格这么低都能满了?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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