1023.驼峰式匹配

【LetMeFly】1023.驼峰式匹配

力扣题目链接:https://leetcode.cn/problems/camelcase-matching/

如果我们可以将小写字母插入模式串 pattern 得到待查询项 query,那么待查询项与给定模式串匹配。(我们可以在任何位置插入每个字符,也可以插入 0 个字符。)

给定待查询列表 queries,和模式串 pattern,返回由布尔值组成的答案列表 answer。只有在待查项 queries[i] 与模式串 pattern 匹配时, answer[i] 才为 true,否则为 false

 

示例 1:

输入:queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FB"
输出:[true,false,true,true,false]
示例:
"FooBar" 可以这样生成:"F" + "oo" + "B" + "ar"。
"FootBall" 可以这样生成:"F" + "oot" + "B" + "all".
"FrameBuffer" 可以这样生成:"F" + "rame" + "B" + "uffer".

示例 2:

输入:queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBa"
输出:[true,false,true,false,false]
解释:
"FooBar" 可以这样生成:"Fo" + "o" + "Ba" + "r".
"FootBall" 可以这样生成:"Fo" + "ot" + "Ba" + "ll".

示例 3:

输出:queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBaT"
输入:[false,true,false,false,false]
解释: 
"FooBarTest" 可以这样生成:"Fo" + "o" + "Ba" + "r" + "T" + "est".

 

提示:

  1. 1 <= queries.length <= 100
  2. 1 <= queries[i].length <= 100
  3. 1 <= pattern.length <= 100
  4. 所有字符串都仅由大写和小写英文字母组成。

方法一:字符串匹配

这道题题目意思稍微有点难以理解,说白了就是:给你n个字符串,返回每个字符串是否符合pattern

怎么样才叫做一个字符串符合pattern呢?

字符串删除数个小写字母后和pattern完全相同就记为“符合”。

这样,对于一个字符串是否符合pattern,我们就有了思路:

使用一个指针来指向pattern的第一个下标(下标0),之后遍历字符串,如果字符串当前字符与指针所指字符匹配,就将指针后移;否则,就尝试删除字符串中的这个字符,怎么删除呢,如果这个字符恰好是小写字母就可用删除,否则(大写字母)的话就没法删除了,就不匹配了。

  • 时间复杂度$O(\sum len(queries[i]) + len(queries)\times len(pattern))$
  • 空间复杂度$O(1)$

AC代码

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
private:
bool isOK(string& q, string& pattern) {
int locP = 0;
for (char c : q) {
if (locP < pattern.size() && pattern[locP] == c) {
locP++;
}
else if (isupper(c)) {
return false;
}
}
return locP == pattern.size();
}

public:
vector<bool> camelMatch(vector<string>& queries, string& pattern) {
vector<bool> ans(queries.size());
for (int i = 0; i < queries.size(); i++) {
ans[i] = isOK(queries[i], pattern);
}
return ans;
}
};

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# from typing import List

class Solution:
def isOK(self, q: str, pattern: str) -> bool:
locP = 0
for c in q:
if locP < len(pattern) and pattern[locP] == c:
locP += 1
elif c.isupper():
return False
return locP == len(pattern)

def camelMatch(self, queries: List[str], pattern: str) -> List[bool]:
ans = [False] * len(queries)
for i in range(len(queries)):
ans[i] = self.isOK(queries[i], pattern)
return ans

同步发文于CSDN,原创不易,转载请附上原文链接哦~
Tisfy:https://letmefly.blog.csdn.net/article/details/130152288


1023.驼峰式匹配
https://blog.letmefly.xyz/2023/04/14/LeetCode 1023.驼峰式匹配/
作者
Tisfy
发布于
2023年4月14日
许可协议