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

数字字符串转化成IP地址

https://www.nowcoder.com/practice/ce73540d47374dbe85b3125f57727e1e

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param s string字符串 
# @return string字符串一维数组
#
class Solution:
    def ser(self, strs, now,  ind, poi):
        if ind>=self.leg:
            return 0
        if poi==2:
            if self.leg-ind<=3:
                if int(self.s[ind:])<=255:
                    if len(self.s[ind:])==1 or int(self.s[ind])>0:
                        news = strs+'.'+self.s[ind:]
                        self.all.append(news)
            return 0
        else:
            if len(now)>0:
                if int(now)>=0 and int(now)<=255:
                    if len(strs)==0:
                        self.ser(now,'',ind,poi)
                    else:
                        news = strs+'.'+now
                        self.ser(news, '', ind,poi+1)
            if len(now)<3:
                if len(now)==0:
                    self.ser(strs, now+self.s[ind],ind+1,poi)
                elif int(now)>0:
                    self.ser(strs, now+self.s[ind],ind+1,poi)

    def restoreIpAddresses(self , s: str) -> List[str]:
        # write code here
        if len(s)==0:
            return []
        
        self.s = s
        self.leg = len(self.s)
        self.all =[]
        self.ser('','',0,0)

        return self.all

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务