字符串
1.字符串变形
swapcase()大小写转换,不用他说的那样全部颠倒顺序,直接就用列表翻转一下内部内容就可以了。
class Solution:
def trans(self , s: str, n: int) -> str:
# write code here
# swapcase()大小写转换
l = s.split(' ') # 将原字符串按照空格分隔成list
l = l[::-1] # 翻转list内的所有单词
s = ""
for letter in l:
letter = letter.swapcase() # 调整大小写
s += letter # 重新串成一个字符串
s += ' '
return s[0:len(s)-1]
2.最长公共前缀
class Solution:
def longestCommonPrefix(self , strs: List[str]) -> str:
# write code here
# 因为是找前缀,所以只用大家都比较前缀就可以,不用比内部最大的相似子串
if not strs:# 列表为空
return ""
result = ""
min_len = min([len(s)for s in strs])
for i in range(min_len):
now = strs[0][i]
if all(s[i]==now for s in strs):
result += now
else:
return result
return result
3.验证IP地址
class Solution:
def is_int(self,i,jinzhi):#对ipv4/ipv6的字符判断,看是否符合条件
try:
int(i,jinzhi)
return True
except:
return False
return False
def solve(self , IP: str) -> str:
# write code here
if '.' in IP:
for ip in IP.split('.'):
if ip.isdigit() is False or ip=='' or ip[0]=='0' or not self.is_int(ip,10) or int(ip)>255 or int(ip)<0:
return 'Neither'
return 'IPv4'
if ':' in IP:
for ip in IP.split(':'):
if (len(ip)>1 and len(ip)==ip.count('0')) or ip=='' or not self.is_int(ip,16):
return 'Neither'
return 'IPv6'
另一个长长的方法,方法都是一样的,只是写的长不长的区别
class Solution:
def is_int(self,i,jinzhi):#对ipv4的字符判断,看是否符合条件
try:
int(i,jinzhi)
return True
except:
return False
return False
def start_zero(self,i):
if len(i)>1 and 0 == int(i[0]):
return False
return True
def solve(self , IP: str) -> str:
if not IP:
return "Neither"
if IP.find('.') >= 0:#判断ip4
a = IP.split('.')
if len(a) != 4:#判断长度
return "Neither"
for i in a:#判断数字
if not self.is_int(i,10) or i.find('-') >= 0:
return "Neither"
if (int(i)<0 or int(i)>255) or not self.start_zero(i):
return "Neither"
return "IPv4"
if IP.find(':') >= 0:#判断ip6
a = IP.split(':')
if len(a) != 8:#判断长度
return "Neither"
for i in a:#判断数字
if not self.is_int(i,16):
return "Neither"
if len(i) > 4 or i.find('-') >= 0:
return "Neither"
return "IPv6"
4.大数加法
class Solution:
def solve(self, s, t):
# """
# 方法一:倒序相加,并反转
# 1,将两个字符串以列表形式拆开,并进行倒序,采用倒序相加的思想
# 2,引入carry值保存两数相加的进位值
# 3,确定最大长度的字符串,并据此建立for循环,循环过程中加入判断:是否较短的字符串已经遍历完,
# 如果遍历完毕,此时设置短字符串位置值为0
# 4,建立保存的字符串结果res,在循环过程中,分别将两个字符串对应的值进行相加取余和取整操作,
# 并将余数添加到res中,取整的部分进入下一轮循环。
# 5,循环完毕后,需要判断最后一步的循环取整操作中,是否存在进位,将进位的值直接加入字符串中
# 6,最后将res结果反转即可
# """
res = ''
if not s and not t:
return res
if len(s) < len(t):
s,t = t,s
s,t=list(s),list(t)
s[:],t[:] = s[::-1],t[::-1]
carry = 0
for i in range(len(s)):
a = int(s[i])
b = 0
if i < len(t):
b = int(t[i])
res = res + str((a+b+carry) % 10)
carry = (a + b + carry) // 10
if carry != 0:
res = res + str(carry)
return res[::-1]
class Solution:
def solve(self, s, t):
n = max(len(s), len(t))
t = t.zfill(n)
s = s.zfill(n)
res = ''
carry = 0
for i in range(n-1,-1,-1):
# for i in range(-1, -n-1, -1):
ans = ord(s[i]) + ord(t[i]) + carry - 96
res = res + str(ans % 10)
carry = ans // 10
if carry != 0:
res = res + str(carry)
return res[::-1]
5.
1.
1.
1.
1.
1.
1.