zoukankan      html  css  js  c++  java
  • LeetCode(58):Length of Last Word

    Length of Last Word:Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.If the last word does not exist, return 0.

    Note: A word is defined as a character sequence consists of non-space characters only.

    For example,
    Given s = "Hello World",
    return 5.

    题意:给定一个字符串,判断最后一个不包括“ ”字符串的长度。

    思路:首先如果字符串如果为空,则返回0,否则,从字符串的最后一个字符开始。查找第一个不为“ ”的索引,然后开始计数,直到找到下一个“ ”返回计数器的值。

    代码:

    public int lengthOfLastWord(String s) {
            int count = 0;
             if(s.length()<=0) return 0;
             int index = s.length() - 1 ;
             while(index>=0&&s.charAt(index)==' ')
             {
                 index--;
             }
             while(index>=0)
             {
                 if(s.charAt(index)!=' ')
                 {
                     count++;
                     index--;
                     if(index<0) return count;
                 }else 
                 {
                     return count;
                }
             }
             return 0;
        }
  • 相关阅读:
    HAOI2015 树上染色
    HAOI2010 软件安装
    T2 Func<in T1,out T2>(T1 arg)
    事无巨细
    LitJson JavaScriptSerializer
    数据库操作
    jQuery:总体掌握
    sql一个题的解法分析讲解
    Javascript系列:总体理解
    c#
  • 原文地址:https://www.cnblogs.com/Lewisr/p/5117833.html
Copyright © 2011-2022 走看看