题目
有效 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 中的任何数字。你可以按 任何 顺序返回答案。
示例
输入:s = “25525511135”
输出:[“255.255.11.135”,“255.255.111.35”]
解析
这道题可以是上一道分割字符串题目的加强版,与之前题目有所不同的是,这次的返回结果是一个一维数组;
func restoreIpAddresses(s string) []string {
var path []string
var res []string //返回结果和之前的不同,都拼在一个数组里
backtracking(s, path, 0, &res)
return res
}
func backtracking(s string, path []string, startIndex int, res *[]string) {
// 终止条件
if startIndex == len(s) && len(path) == 4 {
temp := path[0] + "." + path[1] + "." + path[2] + "." + path[3]
*res = append(*res, temp)
return
}
for i := startIndex; i < len(s); i++ {
if isNormal(s, startIndex, i+1) && i - startIndex + 1 <= 3 {
path = append(path, s[startIndex : i+1])
backtracking(s, path, i+1, res)
} else{
continue
}
path = path[:len(path)-1]
}
}
func isNormal(s string, start int, end int) bool {
checkInt, _ := strconv.Atoi(s[start:end])
if end-start > 1 && s[start] == '0' { //0开始的不合法,但只有0是合法的
return false
}
if checkInt > 255 { //大于255的不合法
return false
}
return true
}
又重做了一遍这道题,这道题的总体思路都是和上一道的分割回文串是很像的,都属于分割问题,但有如下几点需要关注:
- 最后返回的是一个一维数组,那么在定义res和path的时候,可以考虑都定义成一维数组,满足追加进res的条件后,将path分割成段并用“.”连接;
- 第二个就是在追加path的时候,以前都是追加一个元素,本次可能是追加一个切片进去,根据上一题的规律,切片的范围是s[startIndex, i+1];同时要注意调用判断是否满足递归的条件的时候,也是end的下标要+1(上一道题不加,上一道不需要下标切割范围,只是用来判断回文)
- 题目给的是字符串类型,在判断是否和0相等的时候,是用’0’来比较
func restoreIpAddresses(s string) []string {
var res []string
var path []string
if len(s) <= 0 {
return res
}
backTracking(s, 0, path, &res)
return res
}
func backTracking(s string, startIndex int, path []string, res *[]string) {
// 终止条件
if startIndex == len(s) && len(path) == 4 {
temp := path[0] + "." + path[1] + "." + path[2] + "." + path[3]
*res = append(*res, temp)
return
}
for i := startIndex; i < len(s); i++ {
if isValid(s, startIndex, i) { // 这里不+1的话,函数中的end就要+1
path = append(path, s[startIndex:i+1])
backTracking(s, i+1, path, res)
} else {
continue
}
path = path[:len(path)-1]
}
}
func isValid(s string, start, end int) bool {
checkInt, _ := strconv.Atoi(s[start : end+1])
if end-start > 0 && s[start] == '0' { // 注意这个'0'
return false
}
if checkInt > 255 {
return false
}
return true
}