题解 | #数字字符串转化成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
        std::vector<string> res;
        for (int i = 1; i < 4; i++) {
            for (int j = i + 1; j < i + 4; j++) {
                for (int k = j + 1; k < j + 4; k++) {
                    if (s.size() - k > 3 || s.size() - k < 1) {
                        continue;
                    } 
                    std::string a = s.substr(0, i);
                    std::string b = s.substr(i, j - i);
                    std::string c = s.substr(j, k - j);
                    std::string d = s.substr(k);
                    std::cout << "a: " << a << ", b:" << b << ",c:" << c << ",d:" << d << std::endl;
                    if (stoi(a) > 255 || (a.size() > 1 && a[0] == '0') || 
                        stoi(b) > 255 || (b.size() > 1 && b[0] == '0') ||
                        stoi(c) > 255 || (c.size() > 1 && c[0] == '0') ||
                        stoi(d) > 255 || (d.size() > 1 && d[0] == '0')) {
                        continue;
                    }
                    std::string tmp = a + "." + b + "." + c + "." + d;
                    res.push_back(tmp);
                }
            }
        }

        return res;
    }
};

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务