当前位置:网站首页>1108. Defanging an IP Address

1108. Defanging an IP Address

2022-06-22 05:10:00 SUNNY_ CHANGQI

The description of the problem

Given a valid (IPv4) IP address, return a defanged version of that IP address.

A defanged IP address replaces every period "." with "[.]".

 source : Power button (LeetCode)
 link :https://leetcode.cn/problems/defanging-an-ip-address

an example

Input: address = "1.1.1.1"
Output: "1[.]1[.]1[.]1"

The codes for above problem

#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
class Solution {
    
public:
    string defangIPaddr(string address) {
    
        // split the address by '.' into a vector
        string res = "";
        vector<string> address_parts;
        string part;
        while (find(address.begin(), address.end(), '.') != address.end()) {
    
            part = address.substr(0, address.find('.'));
            address_parts.emplace_back(part);
            address.erase(0, address.find('.') + 1);
        }
        for (auto address_part : address_parts) {
    
            res +=  address_part + "[.]";
        }
        res += address;
        return res;
    }
};
int main()
{
    
    Solution s;
    string address = "255.100.50.0";
    cout << "The defanged address is: " << s.defangIPaddr(address) << endl;
    return 0;
}

The corresponding codes

$ ./test
The defanged address is: 255[.]100[.]50[.]0

 Insert picture description here

原网站

版权声明
本文为[SUNNY_ CHANGQI]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206220506112592.html