leetcode刷题(第2047题)——句子中的有效单词数

x33g5p2x  于2022-04-10 转载在 其他  
字(1.1k)|赞(0)|评价(0)|浏览(215)

一、题目

二、示例

输入:sentence = "cat and  dog"
输出:3
解释:句子中的有效单词是 "cat"、"and" 和 "dog"
输入:sentence = "!this  1-s b8d!"
输出:0
解释:句子中没有有效单词
"!this" 不是有效单词,因为它以一个标点开头
"1-s" 和 "b8d" 也不是有效单词,因为它们都包含数字
输入:sentence = "alice and  bob are playing stone-game10"
输出:5
解释:句子中的有效单词是 "alice"、"and"、"bob"、"are" 和 "playing"
"stone-game10" 不是有效单词,因为它含有数字.

三、代码展示

/**
 * @param {string} sentence
 * @return {number}
 */
 var countValidWords = function(sentence) {
  sentence = sentence.trim().replace(/\s+/g, ' ')
  const arr = sentence.split(' ')
  const a = new Set(['!', '.', ',', ' '])
  let ans = 0
  const check = (x) => x.charCodeAt(0) >= 97 && x.charCodeAt(0) <= 122
  for(const s of arr){
      let flag = true
      let cnt1 = 0, cnt2 = 0
      for(let i = 0; i<s.length; i++){
          const ch = s[i]
          if(a.has(ch)){
              cnt1++
          } else if(ch === '-'){
              if(i === 0 || i === s.length-1 || !check(s[i-1]) || !check(s[i+1])){
                  flag = false
              }
              cnt2++
          }else if(!check(ch)) flag = false
      }
      if(flag && cnt1 < 2  && cnt2 < 2){
          if(cnt1 > 0 && a.has(s[s.length-1])){
              ans++
          }else if(cnt1 === 0){
              ans++
          }
      }
  }
  return ans
};

四、总结

相关文章

微信公众号

最新文章

更多