From 78ae0f196cc279110f655e4614cfe469ea0c75b6 Mon Sep 17 00:00:00 2001 From: Yuhao Ju Date: Thu, 8 Dec 2022 21:14:57 +0800 Subject: [PATCH] =?UTF-8?q?update=200093.=E5=A4=8D=E5=8E=9FIP=E5=9C=B0?= =?UTF-8?q?=E5=9D=80:=20=E6=9B=BF=E6=8D=A2=20go=20=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0093.复原IP地址.md | 78 +++++++++++++++------------------ 1 file changed, 36 insertions(+), 42 deletions(-) diff --git a/problems/0093.复原IP地址.md b/problems/0093.复原IP地址.md index ce62cac1..97178cd5 100644 --- a/problems/0093.复原IP地址.md +++ b/problems/0093.复原IP地址.md @@ -424,6 +424,42 @@ class Solution: return True ``` +## Go + +```go +var ( + path []string + res []string +) +func restoreIpAddresses(s string) []string { + path, res = make([]string, 0, len(s)), make([]string, 0) + dfs(s, 0) + return res +} +func dfs(s string, start int) { + if len(path) == 4 { // 够四段后就不再继续往下递归 + if start == len(s) { + str := strings.Join(path, ".") + res = append(res, str) + } + return + } + for i := start; i < len(s); i++ { + if i != start && s[start] == '0' { // 含有前导 0,无效 + break + } + str := s[start : i+1] + num, _ := strconv.Atoi(str) + if num >= 0 && num <= 255 { + path = append(path, str) // 符合条件的就进入下一层 + dfs(s, i+1) + path = path[:len(path) - 1] + } else { // 如果不满足条件,再往后也不可能满足条件,直接退出 + break + } + } +} +``` ## JavaScript @@ -494,48 +530,6 @@ function restoreIpAddresses(s: string): string[] { }; ``` -## Go - -回溯(对于前导 0的IP(特别注意s[startIndex]=='0'的判断,不应该写成s[startIndex]==0,因为s截取出来不是数字)) - -```go -func restoreIpAddresses(s string) []string { - var res,path []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{ - tmpIpString:=path[0]+"."+path[1]+"."+path[2]+"."+path[3] - *res=append(*res,tmpIpString) - } - for i:=startIndex;i1&&s[startIndex]=='0'{//对于前导 0的IP(特别注意s[startIndex]=='0'的判断,不应该写成s[startIndex]==0,因为s截取出来不是数字) - return false - } - if checkInt>255{ - return false - } - return true -} - -``` - ## Rust ```Rust