• [Leetcode] 58. Length of Last Word


    Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string.

    If the last word does not exist, return 0.

    Note: A word is defined as a maximal substring consisting of non-space characters only.

    Example:

    Input: "Hello World"
    Output: 5

    最后一个单词的长度。弱智题,直接上代码了。记得要把input先trim一下,去掉前后多余的空格。

    时间O(n)

    空间O(1)

    JavaScript实现

     1 /**
     2  * @param {string} s
     3  * @return {number}
     4  */
     5 var lengthOfLastWord = function (s) {
     6     // corner case
     7     if (s === null || s.length === 0) {
     8         return 0;
     9     }
    10 
    11     // normal case
    12     let input = s.trim();
    13     let count = 0;
    14     for (let i = input.length - 1; i >= 0; i--) {
    15         if (input[i] !== ' ') {
    16             count++;
    17         } else {
    18             break;
    19         }
    20     }
    21     return count;
    22 };

    Java实现

     1 class Solution {
     2     public int lengthOfLastWord(String s) {
     3         // corner case
     4         if (s == null || s.length() == 0) {
     5             return 0;
     6         }
     7         
     8         // normal case
     9         String input = s.trim();
    10         int count = 0;
    11         for (int i = input.length() - 1; i >= 0; i--) {
    12             if (input.charAt(i) != ' ') {
    13                 count++;
    14             }
    15             else {
    16                 break;
    17             }
    18         }
    19         return count;
    20     }
    21 }

    LeetCode 题目总结

  • 相关阅读:
    仿jquery 选择器功能
    多个div拖拽功能
    js 模拟jquery onready 事件
    随着鼠标移动的图片百叶窗效果
    计算体重引发的思考
    js 模拟事件
    表单验证功能(利用冒泡功能)
    视频播放滚动条(最终完善版)
    仿制视频播放滚动条效果(加左右控制按钮)
    无极树(待整理)
  • 原文地址:https://www.cnblogs.com/cnoodle/p/12016284.html
Copyright © 2020-2023  润新知