zoukankan      html  css  js  c++  java
  • [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 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.

    Example:

    Input: "Hello World"
    Output: 5

    思路:

    给一个字符串,判定最后一个单词的字母的个数。可以从后往前计数,直到遇见空格为止。
    预处理:先把字符串后面的空格都去掉:
    先用length表示s的长度-1,判定这个s.charAt(length)是否等于空格,即最后一位是否为空格,如果是length--,然后继续判断,直到不是空格开始计数。
    从i=length开始,i递减遍历s,如果等于空格则break,如果不等则count++
    返回count即可

     1 public class Solution58 {
     2     public int lengthOfLastWord(String s){
     3         int count = 0;
     4         if(s.isEmpty()) return 0;
     5         int length = s.length()-1;
     6         while(length>0 && s.charAt(length) ==' ') --length;
     7         for(int i = length;i>=0;i--){
     8             if(s.charAt(i) == ' '){
     9                 break;
    10             }else {
    11                 count++;
    12             }
    13         }
    14         //if(count == s.length()){return 0;}
    15         return count;
    16     }
    17     public static void main(String[] args) {
    18         // TODO Auto-generated method stub
    19         String s = "Hello world";
    20         Solution58 solution58 = new Solution58();
    21         System.out.println(solution58.lengthOfLastWord(s));
    22     }
    23 
    24 }
  • 相关阅读:
    Video视频播放中断问题排查记录
    下一站:手机安全
    数据之美 之一
    数据之美 之二
    数据之美 之三
    Groovy入门
    Java8新特性(Lambda表达式、Stream流、Optional类)等
    websocket和ajax的区别(和http的区别)
    java泛型<? extends E>和<? super E>的区别和适用场景
    JAVA反射
  • 原文地址:https://www.cnblogs.com/zlz099/p/8144964.html
Copyright © 2011-2022 走看看