1108. Defanging an IP Address

2019-10-22  本文已影响0人  守住这块热土

1. 题目链接:

https://leetcode.com/problems/defanging-an-ip-address/

Given a valid (IPv4) IP address, return a defanged version of that IP address.
A defanged IP address replaces every period "." with "[.]".

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

Example 2:
Input: address = "255.100.50.0"
Output: "255[.]100[.]50[.]0"

2. 题目关键词


3. 解题思路

遍历字符串address,将'.'替换为[.]

3.1 C语言解题
char * defangIPaddr(char * address){
    int addrLen = strlen(address);
    int defangLen = addrLen + 6 + 1; // 2*3 + 1(结束符)
    
    // 分配内存:defangaddr保证不修改address的值
    char *defangaddr = (char *)malloc(defangLen);
    if (defangaddr == NULL) {
        return NULL;
    }
    
    int j = 0;
    for (int i = 0; i < addrLen; i++) {
        defangaddr[j] = address[i];  // 更新defangaddr
        if (address[i] == '.') {
            defangaddr[j++] = '[';
            defangaddr[j++] = '.';
            defangaddr[j] = ']';
        }
        j++;
    }
    defangaddr[j] = '\0';
    
    return defangaddr;
}

由于C语言不支持string等操作(不支持STL模板),因此代码实现起来略显麻烦。

3.2 C++语言解题
class Solution {
public:
    string defangIPaddr(string address) {        
        return regex_replace(address, regex("[.]"), "[.]");
    }
};
上一篇 下一篇

猜你喜欢

热点阅读