Description
A query word matches a given pattern
if we can insert lowercase
letters to the pattern word so that it equals the query
. (We may insert each character at any position, and may insert 0 characters.)
Given a list of queries
, and a pattern, return an answer
list of booleans, where answer[i]
is true if and only if queries[i]
matches the pattern.
如果我们可以将小写字母插入模式串 pattern
得到待查询项 query
,那么待查询项与给定模式串匹配。(我们可以在任何位置插入每个字符,也可以插入 0 个字符。)
给定待查询列表 queries
,和模式串 pattern
,返回由布尔值组成的答案列表 answer
。只有在待查项 queries[i]
与模式串 pattern
匹配时, answer[i]
才为 true
,否则为 false
。
题目链接:https://leetcode.com/problems/camelcase-matching/
Difficulty: medium
Example 1:
Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FB"
Output: [true,false,true,true,false]
Explanation:
"FooBar" can be generated like this "F" + "oo" + "B" + "ar".
"FootBall" can be generated like this "F" + "oot" + "B" + "all".
"FrameBuffer" can be generated like this "F" + "rame" + "B" + "uffer".
Example 2:
Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBa"
Output: [true,false,true,false,false]
Explanation:
"FooBar" can be generated like this "Fo" + "o" + "Ba" + "r".
"FootBall" can be generated like this "Fo" + "ot" + "Ba" + "ll".
Example 3:
Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBaT"
Output: [false,true,false,false,false]
Explanation:
"FooBarTest" can be generated like this "Fo" + "o" + "Ba" + "r" + "T" + "est".
Note:
- 1 <= queries.length <= 100
- 1 <= queries[i].length <= 100
- 1 <= pattern.length <= 100
- All strings consists only of lower and upper case English letters.
分析
- 对每一个query做如下操作:
- 遍历pattern,比较query和pattern,若不等,且当前query为大写字母,退出,匹配失败;
- 反正继续向后匹配,若匹配玩query,但没有匹配玩pattern,失败;
- 匹配完pattern,若生于query没有大写字母,匹配成功,反之,失败;
- 结果存储在res,返回res。
参考代码
class Solution(object):
def camelMatch(self, queries, pattern):
ans=[]
for query in queries:
i=0
judge=True
for p in pattern:
while(judge and i < len(query) and p != query[i]):
if(query[i].isupper()):
judge=False
ans.append(False)
i=len(query)+1
break
i+=1
if(i==len(query)):
ans.append(False)
break
i+=1
else:
while(i<len(query)):
if(query[i].isupper()):
ans.append(False)
break
else:
i+=1
if(i==len(query)):
ans.append(True)
return ans