zoukankan      html  css  js  c++  java
  • 测试面试LeetCode系列:IP地址无效化

    题目

    给你一个有效的 IPv4 地址 address,返回这个 IP 地址的无效化版本。所谓无效化 IP 地址,其实就是用 "[.]" 代替了每个 "."。
     
    示例 1:
     
    输入:address = "1.1.1.1"
    输出:"1[.]1[.]1[.]1"
    示例 2:
     
    输入:address = "255.100.50.0"
    输出:"255[.]100[.]50[.]0"
     
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/defanging-an-ip-address
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    思路

    这道题是典型的字符串操作算法题,可以通过字符替换得到目标字符串。

    解法1

    Python中进行字符替换的函数:str.replace。 
    class Solution(object):
        def defangIPaddr(self, address):
            """
            :type address: str
            :rtype: str
            """
            return address.replace('.','[.]')

    解法2

    先拆再合:利用split进行字符串切分,然后再使用join函数来生成新的字符串。
    class Solution(object):
        def defangIPaddr(self, address):
            """
            :type address: str
            :rtype: str
            """
            return "[.]".join(address.split("."))

    解法3

    遍历字符串,遇到特点字符后进行转换,最终生成新的字符串。
    class Solution(object):
        def defangIPaddr(self, address):
            """
            :type address: str
            :rtype: str
            """
            r_str = ""
            for ch in address:
                if ch == ".":
                    r_str = r_str + '[.]'
                else:
                    r_str = r_str + ch
            return r_str

    各位大神,有其他思路欢迎留言~

    博主:测试生财

    座右铭:专注测试与自动化,致力提高研发效能;通过测试精进完成原始积累,通过读书理财奔向财务自由。

    csdn:https://blog.csdn.net/ccgshigao

    博客园:https://www.cnblogs.com/qa-freeroad/

    51cto:https://blog.51cto.com/14900374

            

  • 相关阅读:
    Max Sum Plus Plus_DP
    Prime Ring Problem_DFS
    Swaps in Permutation _并查集 + 优先队列
    Roadblocks_次短路
    Reward_toposort
    确定比赛名次_toposort
    Zipper_DFS
    Chopsticks_DP
    搬寝室_DP
    Passing the Message_单调栈
  • 原文地址:https://www.cnblogs.com/qa-freeroad/p/14153145.html
Copyright © 2011-2022 走看看