前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >打卡群刷题总结0803——复原IP地址

打卡群刷题总结0803——复原IP地址

作者头像
木又AI帮
发布2020-08-05 14:23:23
2710
发布2020-08-05 14:23:23
举报
文章被收录于专栏:木又AI帮木又AI帮

题目:93. 复原IP地址

链接:https://leetcode-cn.com/problems/restore-ip-addresses/

给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。 有效的 IP 地址正好由四个整数(每个整数位于 0 到 255 之间组成),整数之间用 '.' 分隔。 示例: 输入: "25525511135" 输出: ["255.255.11.135", "255.255.111.35"]

解题:

1、类似于DFS回溯解法。

代码:

代码语言:javascript
复制
class Solution(object):
    # 判断是否有效
    def isValid(self, s):
        if len(s) >1 and s[0] == '0':
            return False
        if 0 <= int(s) <= 255:
            return True
        return False
    
    def split(self, s, start, num, current):
        # 数字长度是否满足要求
        if len(s) - start < num or len(s) - start > 3 * num:
            return 
        # 只有一位时,判断是否有效
        if num == 1:
            if self.isValid(s[start:]):
                current2 = copy.copy(current)
                current2.append(s[start:])
                self.res.append('.'.join(current2))
            return
        # 其他情况,split
        for i in range(start + 1, len(s) - num + 2):
            if self.isValid(s[start: i]):
                current2 = copy.copy(current)
                current2.append(s[start: i])
                self.split(s, i, num - 1, current2)
            else:
                break
        
    def restoreIpAddresses(self, s):
        """
        :type s: str
        :rtype: List[str]
        """
        self.res = []
        self.split(s, 0, 4, [])
        return self.res
        
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-08-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 木又AI帮 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 链接:https://leetcode-cn.com/problems/restore-ip-addresses/
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档