字符串总结

最长公共前缀

【给你一个大小为 n 的字符串数组 strs ,其中包含n个字符串 , 编写一个函数来查找字符串数组中的最长公共前缀,返回这个公共前缀。】

class Solution:
    def longestCommonPrefix(self , strs: List[str]) -> str:
        # write code here
        res = ''
        for i in zip(*strs):
            if len(set(i)) == 1:
                res += i[0]
            else:
                break
        return res

大数加法

【以字符串的形式读入两个数字,编写一个函数计算它们的和,以字符串形式返回。】

class Solution:
    def solve(self , s: str, t: str) -> str:
        # write code here
        
        if len(s) < len(t): s = "0"*(len(t)-len(s)) + s
        else: t = "0"*(len(s)-len(t)) + t
        s = s[::-1]
        t = t[::-1]
        flag = 0
        result = ""
        print(s,t)
        
        for i in range(len(s)):
            temp = int(s[i]) + int(t[i]) + flag
            if temp >= 10:
                result += str(temp%10)
                flag = 1
                
            else:
                if temp >= 10:
                    
                    result += str(temp%10)
                    flag = 1
                else:
                    result += str(temp)
                    flag = 0
        if flag == 1:result += str(flag)
        return result[::-1]

验证IP地址
在这里插入图片描述

class Solution:
    def solve(self , IP: str) -> str:
        # write code here
        ip4 = IP.split(".")
        ip6 = IP.split(":")
        print(ip4,ip6)
        if len(ip4) != 4 and len(ip6)!=8:
            return "Neither"
    
        if len(ip4)==4:
            for x in ip4:
                if not x.isdigit(): return "Neither"
                if int(x) < 0 or int(x)>255:
                    return "Neither"
                if x[0]=="0" and int(x)!=0:
                    return "Neither"
            return "IPv4"
        
        if len(ip6)==8:
            for x in ip6:
                if len(x)>4 or len(x)==0:
                    return "Neither"
               
                if not x.isalnum():
                    return "Neither"
                for c in x:
                    if not (c.isdigit() or c>="a" and c<="f" or c>="A" and c<="F"):
                        return "Neither"
             
            return "IPv6"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值