Leecode 1023. Camelcase Matching
1023. Camelcase Matching
Given an array of strings queries and a string pattern, return a boolean array answer where answer[i] is true if queries[i] matches pattern, and false otherwise.
A query word queries[i] matches pattern if you can insert lowercase English letters into the pattern so that it equals the query. You may insert a character at any position in pattern or you may choose not to insert any characters at all.
Example 1:
1 | Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FB" |
Example 2:
1 | Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBa" |
Example 3:
1 | Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBaT" |
题目大意
给定字符串数组 queries
和字符串 pattern
,返回一个布尔数组 answer
,其中 answer[i]
为 true
表示 queries[i]
与 pattern
匹配,否则为 false
。
匹配规则:若能在 pattern
中插入任意数量的小写英文字母(也可插入 0 个),使其最终等于 queries[i]
,则认为两者匹配。插入操作不改变 pattern
原有字符的顺序,且只能插入小写字母。
解题思路
核心是通过双指针遍历验证 query
是否能由 pattern
插入小写字母得到,关键在于先定义 “判断字符是否为大写字母” 的函数对象,再基于此实现匹配逻辑:
- 函数对象定义:创建
IsUpper
函数对象,用于快速判断单个字符是否为大写英文字母(A-Z)。 - 双指针匹配逻辑:
- 对每个
query
和pattern
分别用指针q_idx
和p_idx
遍历; - 若
query[q_idx] == pattern[p_idx]
:说明当前字符匹配,两个指针同时后移; - 若
query[q_idx]
是大写字母:此时若无法与pattern
当前字符匹配(p_idx
已越界或字符不相等),则query
必不匹配; - 若
query[q_idx]
是小写字母:直接跳过(视为插入的字符),仅q_idx
后移;
- 对每个
- 最终校验:遍历结束后,需确保
pattern
已完全匹配(p_idx
到达末尾),且query
剩余字符无大写字母(避免未匹配的大写字母残留)。
1 | #include <vector> |
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.