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

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

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

相关推荐

头像
2024-12-19 18:11
英特尔_Software_engineer
下水道鼠鼠鼠鼠:男的能去当技师吗 好进吗
点赞 评论 收藏
分享
2024-12-09 12:21
门头沟学院 C++
l11hy:今早刚开,已满足
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务