目的:熟悉python
7. 整数反转
题目链接:https://leetcode-cn.com/problems/reverse-integer/
思路1
将输入转变为字符串,利用切片x[::-1]
实现反转。
需要注意的点:
- 判断是否负数,是的话,利用
0-int(x)
得到负数 - 判断反转后整数是否在范围内
思路2
实际上只要拿到输入的末尾数字就可以了
需要注意的点
- 不能直接把反转后的数字和要求的范围去比较,因为根据题意,环境不允许存储 64 位整数。所以比较时,少一位比。
看了官方题解, 不太好理解,还是用麻烦一点的。
class Solution:
def reverse(self, x: int) -> int:
MIN = -pow(2, 31) // 10 # -2147483648
MAX = (pow(2, 31) - 1) // 10 # 2147483647
x1 = abs(x)
res = 0
while x1 != 0:
# 弹出末尾的数字
temp = x1 % 10
# 判断是否在范围内
if res < MIN or res == MIN and temp < -8:
return 0
if res > MAX or res == MAX and temp > 7:
return 0
res = res * 10 + temp
x1 = x1 // 10
if x < 0:
return 0 - res
else:
return res
9. 回文数
题目链接:https://leetcode-cn.com/problems/palindrome-number/
思路1
将整数转换为字符串,然后反转字符串,再和原字符串相比较
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
x = str(x)
x1 = x[::-1]
return x == x1
思路2
官方题解: 取出后半段数字进行翻转
class Solution:
def isPalindrome(self, x: int) -> bool:
# 负数和个位为0的非一位数必定不是回文数
if x < 0 or (x % 10 == 0 and x // 10 != 0):
return False
# 去除后半段数字进行翻转
# 关键问题:如何知道取了一半了
# 回答:前半段小于等于后半段
x1 = 0
while x > x1:
x1 = x1 * 10 + x % 10
x = x // 10
# 原x有奇数个数字
if x < x1:
x1 = x1 // 10
return x == x1
13. 罗马数字转整数
题目链接:https://leetcode-cn.com/problems/roman-to-integer/
思路1
利用字典把罗马字母和对应的数字连接在一起,然后对特殊情况特殊处理
class Solution:
def romanToInt(self, s: str) -> int:
dic = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
res = 0
for i, ch in enumerate(s):
value = dic[ch]
if i < len(s) - 1 and value < dic[s[i+1]]:
res -= value
else:
res += value
return res
14. 最长公共前缀
题目链接:https://leetcode-cn.com/problems/longest-common-prefix/
思路1
一次比较
class Solution:
def longestCommonPrefix(self, strs):
# 字符串数组为空或者只有一个元素
if not strs:
return strs
# 拿第一个字符串一次与其他字符串比较
s = strs[0]
for i in range(1, len(strs)):
s = self.compareStr(s, strs[i])
if s == "":
return ""
return s
def compareStr(self, str1, str2):
length = min(len(str1), len(str2))
s = ""
for i in range(length):
if str1[i] == str2[i]:
s = s + str1[i]
else:
break
return s
20. 有效的括号
题目链接:https://leetcode-cn.com/problems/valid-parentheses/
思路1
依次遍历字符串,遇到左括号入栈,遇到右括号,匹配则出栈
class Solution:
def isValid(self, s: str) -> bool:
if len(s) % 2 == 1:
return False
dic = {")": "(", "]": "[", "}": "{"}
strs = list()
for ch in s:
if ch in dic:
if not strs or strs[-1] != dic[ch]:
return False
strs.pop()
else:
strs.append(ch)
return not strs
21. 合并两个有序链表
题目链接:https://leetcode-cn.com/problems/merge-two-sorted-lists/
思路1
递归,每次都是找最小的值,然后递归连接后面的
c++中的c1 == null
等价于 python的not c1
来自题解
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1:
return l2
if not l2:
return l1
if l1.val <= l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1,l2.next)
return l2