题解 | 数字字符串转化成IP地址

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param s string字符串 
# @return string字符串一维数组
#
class Solution:
    def restoreIpAddresses(self , s: str) -> List[str]:
        # write code here
        result = []
        if len(s) < 4:
            return result

        for left in range(1, 4):
            for right in range(1, 4):
                center_length = len(s) - len(s[:left]) - len(s[-right:])
                center_data = s[left: left + center_length]
                if int(s[:left]) <= 255 and s[:left] == str(int(s[:left])) and\
                        int(s[-right:]) <= 255 and s[-right:] == str(int(s[-right:])) and center_length <= len(s) - 2:
                    for p in range(1, center_length):
                        if int(center_data[:p]) <= 255 and center_data[:p] == str(int(center_data[:p])) and\
                                int(center_data[p:]) <= 255 and center_data[p:] ==  str(int(center_data[p:])):
                            result.append(s[:left] + "." + center_data[:p] + "." + center_data[p:] + "." + s[-right:])
        return result

全部评论

相关推荐

VirtualBool:都去逗他了?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务