1、LeetCode----242. 有效的字母异位词
https://leetcode-cn.com/problems/valid-anagram/submissions/
Solution1
#首先考虑将两个字符串转换为列表,遍历其中一个列表
#如果数据在另外一个列表中,删除另外一个列表中的数据直至结束
#当能够完成所有的遍历,说明返回true
#当然应该首先考虑的是两字符串是否长度相等,如果不相等则肯定返回false
class Solution1:
def isAnagram(self, s: str, t: str) -> bool:
s = list(s)
t = list(t)
if len(s)!=len(t):
return 0
for i in s:
if i in t:
t.remove(i)
else:
return 0
return 1
Solution2
#我们可以通过直接将两个字符串转换成列表进行排序
#最后检查两个列表是否相等
#这样做减少了一个数量级的时间复杂度
class Solution2:
def isAnagram(self, s: str, t: str) -> bool:
s = list(s)
s.sort()
t = list(t)
t.sort()
if not s and not t:
return 1
if not s or not t:
return 0
if s == t:
return 1
else:
return 0
Solution3
#若果知道python的一个sorted函数的话,代码可以说非常简洁
#直接排序两个字符串检查是否相等,返回检查的结果
class Solution3:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t)
2、LeetCode----15. 三数之和
https://leetcode-cn.com/problems/3sum/
基本思路
#首先能够想到的是使用三层遍历
#但是我们可以优化到两层,应为到第二层的时候我们就应该知道对应的第三个数是什么
#求前两个数的和的相反数就是第三数,只要检查这个数是否在列表中即可
#但是可惜是最后的两个case还是跑不过,时间超时了。
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
if not nums:
return
n = len(nums)
if n < 3:
return
answer = []
for i in range(n):
check = nums.copy()
check.remove(nums[i])
for j in range(i + 1, n):
check.remove(nums[j])
tem = -(nums[i] + nums[j])
if tem in check:
temp = sorted([nums[i], nums[j], tem])
if temp not in answer:
answer.append(temp)
return answer