1108. Defanging an IP Address

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. 題目關(guān)鍵詞

  • 難度等級:easy
  • 關(guān)鍵詞:
  • 語言: C/C++

3. 解題思路

遍歷字符串a(chǎn)ddress,將'.'替換為[.]

3.1 C語言解題
char * defangIPaddr(char * address){
    int addrLen = strlen(address);
    int defangLen = addrLen + 6 + 1; // 2*3 + 1(結(jié)束符)
    
    // 分配內(nèi)存: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模板),因此代碼實現(xiàn)起來略顯麻煩。

3.2 C++語言解題
  • 使用C++的string.replace函數(shù)替換
  • 替換,查找:正好是正則表達式的強項:
class Solution {
public:
    string defangIPaddr(string address) {        
        return regex_replace(address, regex("[.]"), "[.]");
    }
};
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容