巧妙运用最短补全词,敲开解题之路
2023-11-19 06:11:48
引言
算法面试中,字符串操作题可谓一道道拦路虎,想成功过关,唯有熟练掌握各种字符串匹配技巧。LeetCode 92.最短补全词便是其中一道经典题目,它不仅考察你的算法思维,还考验你对字符串操作的理解深度。本文将带领你深入剖析此题,从题解入手,逐层剥离问题本质,教你巧妙运用字符串匹配技巧,轻松解题,为算法面试之路保驾护航。
原题样例:最短补全词
给你一个字符串 licensePlate 和一个字符串数组 words ,请你找出并返回 words 中最短的补全词。补全词的定义为:当 licensePlate 中的每个字母都可以在 words 中找到时,那么 words 中的这个字符串就是 licensePlate 的补全词。注意:大小写有区别。
示例 1:
输入:licensePlate = "1s3 PSt", words = ["step", "steps", "stripe", "stepple"]
输出:"step"
示例 2:
输入:licensePlate = "1s3 456", words = ["looks", "pest", "stew", "show"]
输出:"pest"
问题本质
乍一看,这道题似乎有些复杂,但如果你能剥离表象,深入挖掘问题的本质,你会发现它其实考察的重点在于字符串匹配。本质上,你需要找出 words 中所有包含 licensePlate 中所有字母的字符串,再从中选出最短的那个。
巧用字符串匹配技巧
要解决这道题,巧妙运用字符串匹配技巧至关重要。这里推荐两种常见的匹配方法:
1. 哈希表法:
哈希表以键值对的形式存储数据,利用其快速查找和检索的特性,我们可以将 licensePlate 中的每个字符作为键,出现次数作为值,存储在一个哈希表中。然后,遍历 words 中的每个字符串,将该字符串中的每个字符与其在哈希表中的对应值进行比较。如果哈希表中不存在该字符,或者哈希表中该字符的出现次数小于字符串中该字符的出现次数,则该字符串不是补全词。
2. 计数器法:
计数器法利用数组或字典来记录每个字母出现的次数。我们同样可以将 licensePlate 中的每个字符作为键,出现次数作为值,存储在一个计数器中。然后,遍历 words 中的每个字符串,将该字符串中的每个字符与计数器中的对应值进行比较。如果计数器中不存在该字符,或者计数器中该字符的出现次数小于字符串中该字符的出现次数,则该字符串不是补全词。
具体解法
掌握了字符串匹配技巧后,我们就可以着手编写代码了。下面是两种方法的具体实现:
哈希表法:
def shortestCompletingWord(licensePlate, words):
# 转换为小写并过滤非字母字符
licensePlate = licensePlate.lower()
licensePlate = ''.join(filter(str.isalpha, licensePlate))
# 创建哈希表存储 licensePlate 中字符及其出现次数
char_count = {}
for char in licensePlate:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
# 遍历 words 中的每个字符串
shortest_word = ""
for word in words:
# 创建当前字符串的字符计数器
word_count = {}
for char in word:
if char in word_count:
word_count[char] += 1
else:
word_count[char] = 1
# 检查当前字符串是否满足补全条件
is_completing = True
for char, count in char_count.items():
if char not in word_count or word_count[char] < count:
is_completing = False
break
# 更新最短补全词
if is_completing and (not shortest_word or len(word) < len(shortest_word)):
shortest_word = word
return shortest_word
计数器法:
def shortestCompletingWord(licensePlate, words):
# 转换为小写并过滤非字母字符
licensePlate = licensePlate.lower()
licensePlate = ''.join(filter(str.isalpha, licensePlate))
# 创建计数器存储 licensePlate 中字符及其出现次数
char_count = {}
for char in licensePlate:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
# 遍历 words 中的每个字符串
shortest_word = ""
for word in words:
# 创建当前字符串的字符计数器
word_count = [0] * 26
for char in word:
index = ord(char) - ord('a')
word_count[index] += 1
# 检查当前字符串是否满足补全条件
is_completing = True
for char, count in char_count.items():
index = ord(char) - ord('a')
if word_count[index] < count:
is_completing = False
break
# 更新最短补全词
if is_completing and (not shortest_word or len(word) < len(shortest_word)):
shortest_word = word
return shortest_word
结语
通过本文对 LeetCode 92.最短补全词问题的深入剖析,你已经掌握了解决此类字符串匹配题目的关键技巧。巧妙运用哈希表或计数器法,结合对问题本质的深刻理解,你将能够轻松应对算法面试中的各种字符串操作难题。
牢记,算法面试的真谛在于理解和运用,而非死记硬背。只有真正掌握了算法思想和字符串匹配技巧,你才能在算法面试中游刃有余,一展身手。祝愿你算法面试之路一路畅通,面试成功!