一道很有意思的题
思路:
先遍历pattern构建正则表达式,题目说明了queries和pattern都由英文字母组成,那么就很好构建,pattern里面的每一个字母只能出现一次,而每个字符之间又可以出现0个或多个小写英文字母。构建好之后,遍历queries直接查询即可。
源代码:
JavaScript
/**
* @param {string[]} queries
* @param {string} pattern
* @return {boolean[]}
*/
const camelMatch = (queries, pattern) => {
const ansArr = new Array(queries.length);
let str = '';
for(let i = 0; i < pattern.length; ++i) {
if(i === 0) {
str += '^[a-z]*';
}
str += pattern[i] + '{1}' + '[a-z]*';
if(i === pattern.length - 1) {
str += '$';
}
}
const reg = new RegExp(str);
for(let i in queries) {
if(reg.test(queries[i])) {
ansArr[i] = true;
} else {
ansArr[i] = false;
}
}
return ansArr;
};
TypeScript:
/**
* @param {string[]} queries
* @param {string} pattern
* @return {boolean[]}
*/
const camelMatch = (queries: string[], pattern: string): boolean[] => {
const ansArr: boolean[] = new Array(queries.length);
let str: string = '';
for(let i: number = 0; i < pattern.length; ++i) {
if(i === 0) {
str += '^[a-z]*';
}
str += pattern[i] + '{1}' + '[a-z]*';
if(i === pattern.length - 1) {
str += '$';
}
}
const reg = new RegExp(str);
for(let i in queries) {
if(reg.test(queries[i])) {
ansArr[i] = true;
} else {
ansArr[i] = false;
}
}
return ansArr;
};