为了账号安全,请及时绑定邮箱和手机立即绑定

leetcode 500 键盘行

leetcode 500 键盘行

守着一只汪 2019-08-17 09:27:14
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。为什么会这样?
查看完整描述

2 回答

?
青春有我

TA贡献1784条经验 获得超8个赞

换成以下写法就能通过!
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
};
                            
查看完整回答
反对 回复 2019-08-17
?
ITMISS

TA贡献1871条经验 获得超8个赞

这个是因为你的正则表达式中使用g全局匹配导致的,因为全局匹配一个字符串后会记录匹配的位置,下一次匹配会从上一次匹配成功的位置往后开始匹配。下面的例子能帮助你理解
varreg=/a/g;
console.log(reg.test('aa'));//true
console.log(reg.lastIndex);//1
console.log(reg.test('aa'));//true
console.log(reg.lastIndex);//2
console.log(reg.test('aa'));//false
console.log(reg.lastIndex);//0
所以建议去掉g,且由于LeetCode500题的单词不一定是长度为1的字符串,建议修改为/[qwertyuiop]+/i
                            
查看完整回答
反对 回复 2019-08-17
  • 2 回答
  • 0 关注
  • 223 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号