美文网首页
1108. Defanging an IP Address

1108. Defanging an IP Address

作者: 守住这块热土 | 来源:发表于2019-10-22 11:32 被阅读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. 题目关键词

    • 难度等级:easy
    • 关键词:
    • 语言: C/C++

    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++语言解题
    • 使用C++的string.replace函数替换
    • 替换,查找:正好是正则表达式的强项:
    class Solution {
    public:
        string defangIPaddr(string address) {        
            return regex_replace(address, regex("[.]"), "[.]");
        }
    };
    

    相关文章

      网友评论

          本文标题:1108. Defanging an IP Address

          本文链接:https://www.haomeiwen.com/subject/yezfvctx.html