33/MyCode
/LeetCode/LeetCode_677.py
# LeetCode_677
给定一个只包含小写字母的字符串,找出该字符串中出现次数最多的字母,并返回该字母出现的次数。
注意:该字母可以是任何字母,而且该字母出现次数应该与其它字母不同。
思路:直接遍历字符串,使用字典统计字母出现的次数,返回字典中出现次数最多的字母即可。
时间复杂度:O(n),其中n是字符串长度。
空间复杂度:O(n),需要存储每个字母出现的次数。
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
import re
banned = set(banned)
# 用正则表达式将所有非字母字符转换为空字符串
paragraph = re.sub(r'[^a-zA-Z]', ' ', paragraph).split()
# 用字典统计字母出现的次数
dic = dict()
for word in paragraph:
if word not in dic:
dic[word] = 1
else:
dic[word] += 1
# 返回出现次数最多的字母
return max(dic, key = dic.get)
/LeetCode/LeetCode_676.py
# LeetCode_676
给定一个仅包含���写字母的字符串,找到并返回该字符串中出现次数最多的字母的字母和出现次数。
思路:直接遍历字符串,使用字典统计字母出现的次数,返回字典中出现次数最多的字母即可。
时间复杂度:O(n),其中n是字符串长度。
空间复杂度:O(n),需要存储每个字母出现的次数。
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
import re
# 用正则表达式将所有非字母字符转换为空字符串
paragraph = re.sub(r'[^a-zA-Z]', ' ', paragraph).split()
# 用字典统计字母出现的次数
dic = dict()
for word in paragraph:
if word not in dic:
dic[word] = 1
else:
dic[word] += 1
# 返回出现次数最多的字母
return max(dic, key = dic.get)
/LeetCode/LeetCode_669.py
# LeetCode_669
给定一个只包含小写字母的字符串,找到该字符串中出现次数最多的字母,并返回该字母出现的次数。
注意:该字母可以是任何字母,而且该字母出现次数应该与其它字母不同。
思路:直接遍历字符串,使用字典统计字母出现的次数,返回字典中出现次数最多的字母即可。
时间复杂度:O(n),其中n是字符串长度。
空间复杂度:O(n),需要存储每个字母出现的次数。
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
import re
banned = set(banned)
# 用正则表达式将所有非字母字符转换为空字符串
paragraph = re.sub(r'[^a-zA-Z]', ' ', paragraph).split()
# 用字典统计字母出现的次数
dic = dict()
for word in paragraph:
if word not in dic:
dic[word] = 1
else:
dic[word] += 1
# 返回出现次数最多的字母
return max(dic, key = dic.get)
/LeetCode/LeetCode_1518.py
# LeetCode_1518
给定一个只包含小写字母的字符串,找到该字符串中出现次数最多的字母,并返回该字母出现的次数。
注意:该字母可以是任何字母,而且该字母出现次数应该与其它字母不同。
思路:直接遍历字符串,使用字典统计字母出现的次数,返回字典中出现次数最多的字母即可。
时间复杂度:O(n),其中n是字符串长度。
空间复杂度:O(n),需要存储每个字母出现的次数。
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
import re
# 用正则表达式将所有非字母字符转换为空字符串
paragraph = re.sub(r'[^a-zA-Z]', ' ', paragraph).split()
# 用字典统计字母出现的次数
dic = dict()
for word in paragraph:
if word not in dic:
dic[word] = 1
else:
dic[word] += 1
# 返回出现次数最多的字母
return max(dic, key = dic.get)
/LeetCode/LeetCode_120.py
# LeetCode_120
给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在两个不同的下标 i 和 j,使得 nums[i] + nums[j] == target。如果存在,则返回下标 i 和 j,否则返回 -1。
思路:使用字典来统计数组中每个元素出现的次数,然后遍历字典,找到是否存在满足条件的两个下标。时间复杂度:O(n),空间复杂度:O(n)。
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
import collections
dic = collections.Counter(nums)
for key, value in dic.items():
if target - key in dic:
if target - key == key:
if dic[key] > 1:
return [nums.index(key), nums.index(target - key, nums