题解 | #字符串最后一个单词的长度#

字符串最后一个单词的长度

https://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static int calc(String str){
        str = str.trim();
        int endIndex = str.length()-1;
        while (endIndex >= 0 && str.charAt(endIndex) != ' ') {
            endIndex -- ;
        }
        int startIndex = endIndex + 1;
        String lastword = str.substring(startIndex);    
    return lastword.length();
    }
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
       System.out.print(calc(in.nextLine()));
    }
}

#牛客帮帮团来啦!有问必答#
全部评论
这个解题的关键是找到最后一个单词的开始位置跟介绍位置, 所以从字符串最后一个位置一直往前推,直到看到空格为止。跳出循环后,找到开始位置,即:刚跳出循环的这个位置再往后挪一个位置
点赞 回复 分享
发布于 2024-04-19 20:30 上海

相关推荐

01-26 19:51
门头沟学院 Java
isabener:怎么感觉像群发的呢
点赞 评论 收藏
分享
未知的命运:重新优化一下项目吧,不然你没机会了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务