本文参考自力扣题目
1、9. 回文数
给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如,121 是回文,而 123 不是。
class Solution:
def isPalindrome(self, x: int) -> bool:
y = str(x)[::-1]
return str(x) == y
2、
class Solution:
def romanToInt(self, s: str) -> int:
sing = {
'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
dou = {
'IV': 4,'IX':9, 'XL': 40, 'XC':90, 'CD':400, 'CM':900}
index = 0
num = 0
while index < len(s):
if s[index:index+2] in dou:
num = num + dou[s[index:index+2]]
index = index + 2
else:
num = num + sing[s[index:index+1]]
index = index + 1
return num
3 14. 最长公共前缀
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if len(strs) == 0:
return ""
elif len(strs) == 1:
return strs[0]
elif len(strs) == 2:
num = []
a = strs[0]
b = strs[1]
lenth = min(len(a), len(b))
for i in range(lenth):
if a[i] == b[i]:
num.append(a[i])
else: break
return ''.join(num)
else:
num = []
a = strs[0]
b = strs[1]
lenth1 = min(len(a), len(b))
for i in range(lenth1):
if a[i] == b[i]:
num.append(a[i])
else: break
for _ in range(2, len(strs)):
c = strs[_]
lenth2 = min(len(num), len(c))
newnum = []
for i in range(lenth2):
if num[i] == c[i]:
newnum.append(num[i])
else: break
num = newnum
return ''.join(newnum)
让代码变短!
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs:
return ""
length, count = len(strs[0]), len(strs)
for i in range(length):
c = strs[0][i]
if any(i == len(strs[j]) or strs[j][i] != c for j in range(1, count)):
return strs[0][:i]
return strs[0]