242 有效的字母異位詞(亞馬遜、Facebook、谷歌在半年內面試中考過)
注意切題四件套:
- clarification 和麪試官搞清楚題目的要求,即題面是什麼,比如在本題中需要搞清楚,
- 什麼是異位詞:異位詞是字母出現的次數一樣,但是出現順序不一樣的詞
- 在本題中是否區分大小寫?
- possible solutions—>optimal(time & space)
- code
- test cases
這裏一定要記得和麪試官要幾個測試樣例,證明你做事是有始有終的
本題的方法有:
- 暴力法:先 sort 一下排個序再比較,時間複雜度是 O(nlogn)
- 哈希表的方法:map 來統計每個字符出現的頻次,如果相同證明是異位詞
# 方法1;暴力法
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t)
# 方法2:hashtable 的方法
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return collections. Counter(s) == collections.Counter(t)
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
dic = {}
for item in strs:
key = tuple(sorted(item))
dic[key] = dic.get(key,[]) + [item]
return list(dic.values())
1 兩數之和(亞馬遜、字節跳動、谷歌、Facebook、蘋果、微軟、騰訊在半年內面試中常考)
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dic = {}
for i,num in enumerate(nums):
if num in dic:
return [dic[num],i]
dic[target - num] = i