LeetCode每日一题|434. 字符串中的单词数

193 阅读1分钟

题目描述

题目链接:leetcode-cn.com/problems/nu… image.png

思路分析

两种思路:

第一种,使用split以空格将字符串转化为数组,再统计数组中空格多个空格连在一起时和空串的个数传入字符串为空时,最后返回数组的长度减去空格和空串的个数就是单词数。

第二种,使用match匹配不为空的字符串的数量,该正则表达式为/\S+/g,不过当不存在单词是match会返回null,从而报错,所以需要在得到null时返回0。

代码

  • 思路1

var countSegments = function (s) {
  let arr = s.split(" ");
  let l = 0;
  for (item of arr) {
    if (item == "" || item == " ") {
      l++;
    }
  }
  return arr.length - l;
};
  • 思路2

var countSegments = function (s) {
  return (s.match(/\S+/g) || []).length;
};