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

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

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 上海

相关推荐

嗨害嗨我来了:感谢我吧,上次我在食堂敲打了一个姓雷的,他说马上给大学生们准备hc
不卡学历的大厂有哪些?
点赞 评论 收藏
分享
苍蓝星上艾露:这简历。。。可以试试我写的开源简历优化工具https://github.com/weicanie/prisma-ai
点赞 评论 收藏
分享
07-29 14:27
门头沟学院 Java
LMQICU:大暴雨阁下真的没绷住
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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