Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
restore-ip-addresses.py 1019 Bytes
一键复制 编辑 原始数据 按行查看 历史
Allen Liu 提交于 2018-10-13 13:24 +08:00 . update
# Time: O(n^m) = O(3^4)
# Space: O(n * m) = O(3 * 4)
class Solution(object):
# @param s, a string
# @return a list of strings
def restoreIpAddresses(self, s):
result = []
self.restoreIpAddressesRecur(result, s, 0, "", 0)
return result
def restoreIpAddressesRecur(self, result, s, start, current, dots):
# pruning to improve performance
if (4 - dots) * 3 < len(s) - start or (4 - dots) > len(s) - start:
return
if start == len(s) and dots == 4:
result.append(current[:-1])
else:
for i in xrange(start, start + 3):
if len(s) > i and self.isValid(s[start:i + 1]):
current += s[start:i + 1] + '.'
self.restoreIpAddressesRecur(result, s, i + 1, current, dots + 1)
current = current[:-(i - start + 2)]
def isValid(self, s):
if len(s) == 0 or (s[0] == '0' and s != "0"):
return False
return int(s) < 256
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助