7 - 58. Length of Last Word

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;
 }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容