> 文章列表 > 驼峰式匹配-力扣1023-java

驼峰式匹配-力扣1023-java

驼峰式匹配-力扣1023-java

一、题目描述

如果我们可以将小写字母插入模式串 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".

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/camelcase-matching
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二、运行结果

三、解题思路

对于字符串数组中的每个字符串s,遍历s中的每个字符(ch),使用一个index指向模式串中的当前字符(用于和s中的当前字符进行比较):

如果 ch 和模式串中 index 指向的字符相同(不管大小写),则index后移一位;

如果 ch是大写字符 且  index 已经超出模式串的长度或者 ch 和 index指向的字符不相同,则为不匹配,当前串匹配结束,加入false;

当遍历完 S 后,若模式串还没遍历完,则为不匹配,加入false,否则为匹配,加入true。

四、AC代码

class Solution {public List<Boolean> camelMatch(String[] queries, String pattern) {int qlen = queries.length;int plen = pattern.length();List<Boolean> ans = new ArrayList<>();for(String str : queries){int index = 0;   //指向模式串当前字符boolean flag = true;for(char ch : str.toCharArray()){if(index < plen && ch == pattern.charAt(index)){index++;       //两个串的当前字符相同}else if(ch >= 'A' && ch <= 'Z' &&  (index >= plen || ch != pattern.charAt(index))){flag = false;  //模式串已遍历完或大写字母不相等ans.add(false);break;}}if(flag){   //字符串遍历完没有出现不匹配的项if(index < plen){ //模式串还没有遍历完ans.add(false);}else {            //模式串已经已遍历完ans.add(true);}}}return ans;}
}

中国互联网产业年会