美文网首页
7 - 58. Length of Last Word

7 - 58. Length of Last Word

作者: bestCindy | 来源:发表于2022-06-21 00:04 被阅读0次

https://leetcode.com/problems/length-of-last-word/

var lengthOfLastWord = function (s) {
      let str = trim(s);
      let word = "";

      for (let i = str.length - 1; i >= 0; i--) {
        if (str[i] !== ' ') {
          word += str[i];
          continue;
        }
        break;
      }
      return word.length;
    };

    function trim(str) {
      let start = 0;
      let end = str.length - 1;

      for (let i = 0; i < str.length; i++) {
        if (str[i] === ' ') {
          ++start;
          continue
        }
        break;
      }

      for (let i = str.length - 1; i >= 0; i--) {
        if (str[i] === ' ') {
          --end;
          continue
        }
        break;
      }

      return str.slice(start, end + 1);
    }

I made two mistakes during the process I solve this problem

  • I forgot to add continue in if condition expression
  • I wrote str as s.......... I think I need to pay more attention when writing the code

we can solve this problem in one line with some built-in methods

 var lengthOfLastWord = function (s) {
    return s.trim().split(" ").pop().length;
 }

the first method which is too complexity is my thoughts and there is a better method with similar thoughts in discussion board

 var lengthOfLastWord = function (s) {
    let len = 0;
    let hasStarted = false;
     
    for (let i = s.length - 1; i >=0; i--) {
        if (s[i] !== " ") hasStarted = true;
        if (hasStarted) {
            if (s[i] === " ") break;
            len++;
        }
    }
     
     return len;
 }

相关文章

网友评论

      本文标题:7 - 58. Length of Last Word

      本文链接:https://www.haomeiwen.com/subject/nmlsvrtx.html