两数之和
class Solution:
def twoSum(self, nums, target):
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
if nums[i] + nums[j] == target:
return [i, j]
return []
整数反转
class Solution:
def reverse(self, x: int) -> int:
str_x = str(x)
if str_x[0] == "-":
x= -x
str_x1=str(x)
str_x1 = str_x1[::-1]
x = int(str_x1)
x = -x
if -2147483648 < x < 2147483647:
return x
else: x=0
else:
str_x = str_x[::-1]
x = int(str_x)
if -2147483648 < x < 2147483647:
return x
else: x=0
return x
网站的python3 不支持str_x1[:0:-1]
故多加了几个步骤, 加上2个判断机制。终于过了…
回文比较简答
class Solution:
def isPalindrome(self, x: int) -> bool:
str_x = str(x)
if str_x[0] == “-”:
return False
elif str_x==str_x[::-1]:
return True
else:
return False
罗马字转换
class Solution:
def romanToInt(self, s: str) -> int:
a = {‘I’:1, ‘V’:5, ‘X’:10, ‘L’:50, ‘C’:100, ‘D’:500, ‘M’:1000}
ans=0
for i in range(len(s)):
if i<len(s)-1 and a[s[i]]<a[s[i+1]]:
ans-=a[s[i]]
else:
ans+=a[s[i]]
return ans
学到了可以给字符标志大小来比较,比自己编循环语句节约了不少,看到题解还有hash字典
以后再慢慢理解。
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if len(strs)== 0:
return “”
len_strs=len(strs)
str_minlen=len(strs[0])
for i in range(0,len_strs):#算出此数组中最短的那个字符串的长度
if len(strs[i])<str_minlen:
str_minlen=len(strs[i])
answer=""
for i in range(0,str_minlen):
target=strs[0][i]#取第一个字符串的第i个字母作为比对的标准
for j in range(0,len_strs):#对每一个字符串的第i个字母进行比对
if strs[j][i]!=target:
return answer
answer=answer+target
return answer
学到了 可以在循环里套循环,太久没捡起来 已经忘了,脑袋里有思路不知道怎么实现。
class Solution:
def isValid(self, s: str) -> bool:
dic = {’)’:’(’,’]’:’[’,’}’:’{’}
stack = []
for i in s:
if stack and i in dic:
if stack[-1] == dic[i]: stack.pop()
else: return False
else: stack.append(i)
return not stack
一点也没明白…补知识去