leetcode 500 键盘行

varfindWords=function(words){
letres=[]
letlen1=/[qwertyuiop]/gi;
letlen2=/[asdfghjkl]/gi;
letlen3=/[zxcvbnm]/gi;
for(letitemofwords){
letcount1=len1.test(item)
letcount2=len2.test(item)
letcount3=len3.test(item)
if((count1+count2+count3)===1){
res.push(item)
}
}
returnres
};
当输入findWords(["a","b","c","D","c"])words[2]的正则总是错的!这是什么原因引起的?words[2]count3是false,words[4]count3是true。为什么会这样?
守着一只汪
浏览 224回答 2
2回答

青春有我

换成以下写法就能通过!varfindWords=function(words){letres=[]letlen1=/[qwertyuiop]/gi;letlen2=/[asdfghjkl]/gi;letlen3=/[zxcvbnm]/gi;for(letitemofwords){letsum=~~(item.match(len1)!==null)+~~(item.match(len2)!==null)+~~(item.match(len3)!==null)if(sum===1){res.push(words[i])}}returnres};

ITMISS

这个是因为你的正则表达式中使用g全局匹配导致的,因为全局匹配一个字符串后会记录匹配的位置,下一次匹配会从上一次匹配成功的位置往后开始匹配。下面的例子能帮助你理解varreg=/a/g;console.log(reg.test('aa'));//trueconsole.log(reg.lastIndex);//1console.log(reg.test('aa'));//trueconsole.log(reg.lastIndex);//2console.log(reg.test('aa'));//falseconsole.log(reg.lastIndex);//0所以建议去掉g,且由于LeetCode500题的单词不一定是长度为1的字符串,建议修改为/[qwertyuiop]+/i
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript