17 - 最后一个单词的长度

题目

给定一个仅包含大小写字母和空格‘ ’的字符串,返回其最后一个单词的长度。

如果不存在最后一个单词,请返回0。

说明:一个单词是指由字母组成,但不包含任何空格的字符串。

示例:

输入: "Hello World" 输出: 5

解答

split

就是输入一串字符串,用空格分开,求最后那个字符串的长度。在split之前还要把头尾的空格都去掉。

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLastWord = function(s) {
  const words = s.replace(/(^\s*)|(\s*$)/g, "").split(" ");
  return words[words.length - 1].length;
};

Runtime: 52 ms, faster than 84.23% of JavaScript online submissions for Length of Last Word.

Memory Usage: 33.9 MB, less than 26.21% of JavaScript online submissions for Length of Last Word.

双指针

从后往前遍历,一个指针记录结束点,一个指针记录开始点,最后减一下。

作者:guanpengchn

链接:https://leetcode-cn.com/problems/two-sum/solution/hua-jie-suan-fa-58-zui-hou-yi-ge-dan-ci-de-chang-d/

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLastWord = function(s) {
  let end = s.length - 1;
  while (end >= 0 && s[end] === " ") {
    end--;
  }
  if (end < 0) {
    return 0;
  }
  let start = end;
  while (start >= 0 && s[start] !== " ") {
    start--;
  }
  return end - start;
};

Runtime: 48 ms, faster than 93.79% of JavaScript online submissions for Length of Last Word.

Memory Usage: 33.9 MB, less than 41.59% of JavaScript online submissions for Length of Last Word.

Last updated

Was this helpful?