0093-复原IP地址

有效 IP 地址 正好由四个整数(每个整数位于 0 到 255 之间组成,且不能含有前导 0),整数之间用 '.' 分隔。

例如:"0.1.2.201" 和 "192.168.1.1" 是 有效 IP 地址,但是 "0.011.255.245"、"192.168.1.312" 和 "192.168@1.1" 是 无效 IP 地址。
给定一个只包含数字的字符串 s ,用以表示一个 IP 地址,返回所有可能的有效 IP 地址,这些地址可以通过在 s 中插入 '.' 来形成。你不能重新排序或删除 s 中的任何数字。你可以按 任何 顺序返回答案。

示例 1:

输入:s = "25525511135"
输出:["255.255.11.135","255.255.111.35"]
示例 2:

输入:s = "0000"
输出:["0.0.0.0"]
示例 3:

输入:s = "1111"
输出:["1.1.1.1"]
示例 4:

输入:s = "010010"
输出:["0.10.0.10","0.100.1.0"]
示例 5:

输入:s = "101023"
输出:["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]

提示:

0 <= s.length <= 20
s 仅由数字组成

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/restore-ip-addresses

参考:

python

# 复原IP地址

class Solution:
    def __init__(self):
        self.s = ""
        self.res = []

    def isVaild(self, s: str) -> bool:
        if len(s) > 1 and s[0] == "0":
            return False

        if 0 <= int(s) <= 255:
            return True

        return False

    def backTrack(self, path:[str], start:int):
        if start == len(self.s) and len(path) == 4:
            self.res.append(".".join(path))
            return

        for end in range(start+1, len(self.s)+1):
            # 剪枝
            # 保证切割完没有剩余的字符
            if len(self.s)-end > 3*(4-len(path)-1):
                continue
            if self.isVaild(self.s[start:end]):
                # 参数处更新状态,path变量没有改变,不用pop
                self.backTrack(path+[self.s[start:end]], end)

    def restoreIpAddresses(self, s: str) -> [str]:
        if len(s) > 3*4:
            return []
        self.s = s
        self.backTrack([], 0)
        return self.res

class Solution2:
    def restoreIpAddresses(self, s: str) -> [str]:
        ans = []
        path = []
        def backTrack(path: [str], startIndex: int):
            if len(s)>12:return []
            if len(path) == 4:
                if startIndex == len(s):
                    ans.append(".".join(path[:]))
                    return
            for i in range(startIndex, min(startIndex+4, len(s)+1)): #剪枝
                str_ = s[startIndex:i]
                if not 0 <= int(str_) <= 255:
                    continue
                if not str_ == "0" and not str_.lstrip("0") == str_:
                    continue
                path.append(str_)
                backTrack(path, i)
                path.pop()
        backTrack([], 0)
        return ans

golang

package backTrack

import "strconv"

func restoreIpAddresses(s string) []string {
	var res, path []string
	backtrackIP(s, path, 0, &res)
	return res
}

func backtrackIP(s string, path []string, startIndex int, res *[]string)  {
	// 终止条件
	if startIndex == len(s) && len(path) == 4 {
		tmpIPString := path[0] + "." + path[1] + "." + path[2] + "." + path[3]
		*res = append(*res, tmpIPString)
	}
	for i:=startIndex;i<len(s);i++ {
		// 处理8bit的ip分段
		path := append(path, s[startIndex:i+1])
		if i-startIndex+1 <= 3 && len(path) <= 4 && isVaildIp(s, startIndex,i) {
			// 递归
			backtrackIP(s, path, i+1,res)
		} else {return}
		// 回溯
		path = path[:len(path)-1]
	}

}

func isValidIp(s string, startIndex,end int) bool {
	checkInt,_ := strconv.Atoi(s[startIndex:end+1])
	if end - startIndex + 1 > 1 && s[startIndex] == '0' {
		return false
	}
	if checkInt > 255 {
		return false
	}
	return true
}

posted on 2021-11-21 22:31  进击的davis  阅读(10)  评论(0编辑  收藏  举报

导航