美文网首页算法学习
算法题--解析IP地址

算法题--解析IP地址

作者: 岁月如歌2020 | 来源:发表于2020-04-26 18:18 被阅读0次
image.png

0. 链接

题目链接

1. 题目

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

A valid IP address consists of exactly four integers (each integer is between 0 and 255) separated by single points.

Example:

Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]

2. 思路1:回溯法

  • 利用回溯法, 逐个确定每个数字, 直至得到合法结果; 如果中途失败, 则回溯到上一个选择并撤销
  • 为了增加速度,可以提前排除掉后续数字数不够或超出的选择

3. 代码

# coding:utf8
from typing import List


class Solution:
    def restoreIpAddresses(self, s: str) -> List[str]:
        options = [1, 2, 3]

        def seek(i, n, result, results):
            if n == 0:
                if len(result) == 4 and i == 0:
                    results.add('.'.join([str(x) for x in result]))
            else:
                for option in options:
                    if i < option:
                        continue
                    value = s[i - option: i]
                    if option > 1 and value[0] == '0':
                        continue
                    if option == 3 and value > '255':
                        continue
                    if n > 1 and (i - option < n - 1 or i - option > (n - 1) * 3):
                        continue

                    result.insert(0, value)
                    seek(i - option, n - 1, result, results)
                    result.pop(0)

        rtn_list = set()
        seek(len(s), 4, list(), rtn_list)

        return list(rtn_list)


def my_test(solution, s):
    print('input: {}, output: {}'.format(s, solution.restoreIpAddresses(s)))


solution = Solution()
my_test(solution, '25525511135')
my_test(solution, '0000')
my_test(solution, '010010')

输出结果

input: 25525511135, output: ['255.255.11.135', '255.255.111.35']
input: 0000, output: ['0.0.0.0']
input: 010010, output: ['0.10.0.10', '0.100.1.0']

4. 结果

image.png

相关文章

  • 算法题--解析IP地址

    0. 链接 题目链接 1. 题目 Given a string containing only digits, r...

  • 算法(2)重构IP地址

    LeetCode算法题,重构IP地址 参考DFS-lintcode恢复ip地址(Restore IP Addres...

  • web开发-----菜鸟篇

    一、ip地址 1、1 ip地址解析 ip地址=网咯地址+主机地址 (192.168.100.1) 网络地址: 19...

  • 计网基础题

    IP地址转换 ARP(Address Resolution Protocol):地址解析协议,将ip地址转换成物理...

  • ARP获取

    ARP(Address Resolution Protocol,地址解析协议)是将IP地址解析为以太网MAC地址(...

  • 当你在浏览器输入一个网址,如http://www.baidu.c

    浏览器向DNS服务器请求解析该URL中的域名所对应的IP地址; 解析出IP地址后,根据该IP地址和默认端口80,和...

  • 浏览器从输入URL到渲染完页面的整个过程

    一、获取IP地址 通过DNS将URL解析成IP地址 IP地址对应一台真实的物理机器,而且IP地址就像人的身份证是唯...

  • css方面的认识

    首先认识域名与IP地址 域名:www.baidu.com 通过DNS解析成IP地址 192.168.000.001...

  • HTTP

    一、地址栏键入URL,按下回车发生什么? 1、DNS解析,将相应的域名解析为IP地址 2.客户端根据IP地址去寻找...

  • 网络协议分析-ARP与RARP

    ARP与RARP ARP协议: 地址解析协议,实现从IP地址到MAC地址的映射,询问目标IP对应的MAC地址。 A...

网友评论

    本文标题:算法题--解析IP地址

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