牛客网-华为机试-字符串最后一个单词的长度

题目描述

计算字符串最后一个单词的长度,单词以空格隔开。

输入描述:

一行字符串,非空,长度小于5000。

输出描述:

整数N,最后一个单词的长度。

示例1

输入

hello world

输出

5
import java.util.Scanner;
import java.util.Stack;
public class Main{
    
    public static int computeLastLen(String words) {
        String[] wordArray = words.split(" ");
        return wordArray[wordArray.length - 1].length();
    }
    public static int lastLen(String words) {
        if(words == null) {
            return 0;
        }
        int len = 0;
        boolean showCount = true;
        for(int i = 0; i < words.length(); ++i) {
            if(words.charAt(i) != ' ') {
                if(!showCount){
                    len = 0;
                }
                ++len;
                showCount = true;
            }else if(showCount) {
                showCount = false;
            }
        }
        return len;
    }
    
    public static void main(String[] ars) {
        Scanner sc = new Scanner(System.in);
        String words = sc.nextLine();
        System.out.print(Main.computeLastLen(words));
        sc.close();
    }
}
原文地址:https://www.cnblogs.com/zhouquan-1992-04-06/p/13796099.html