From b57023340989dd6070628ba09766e4ea6b305f59 Mon Sep 17 00:00:00 2001 From: ironartisan Date: Tue, 24 Aug 2021 15:41:42 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00093.=E5=A4=8D=E5=8E=9FIP?= =?UTF-8?q?=E5=9C=B0=E5=9D=80python3=E7=89=88=E6=9C=AC=EF=BC=8C=E6=80=9D?= =?UTF-8?q?=E8=B7=AF=E6=B8=85=E6=99=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0093.复原IP地址.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/problems/0093.复原IP地址.md b/problems/0093.复原IP地址.md index 9a95af22..1d39df75 100644 --- a/problems/0093.复原IP地址.md +++ b/problems/0093.复原IP地址.md @@ -309,7 +309,34 @@ class Solution { ``` python版本: +```python +class Solution: + def restoreIpAddresses(self, s: str) -> List[str]: + res = [] + path = [] # 存放分割后的字符 + # 判断数组中的数字是否合法 + def isValid(p): + if p == '0': return True # 解决"0000" + if p[0] == '0': return False + if int(p) > 0 and int(p) <256: return True + return False + + def backtrack(s, startIndex): + if len(s) > 12: return # 字符串长度最大为12 + if len(path) == 4 and startIndex == len(s): # 确保切割完,且切割后的长度为4 + res.append(".".join(path[:])) # 字符拼接 + return + for i in range(startIndex, len(s)): + p = s[startIndex:i+1] # 分割字符 + if isValid(p): # 判断字符是否有效 + path.append(p) + else: continue + backtrack(s, i + 1) # 寻找i+1为起始位置的子串 + path.pop() + backtrack(s, 0) + return res +``` ```python class Solution(object): def restoreIpAddresses(self, s):