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

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

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

大无语事件, 没仔细看题直接就开始做了, 我以为的题意是: 单词被空格隔开, 输出最长单词的长度.
没想到只用输出最后一个单词的长度.....

这是本题题解:

import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String S = in.nextLine();
        int current = 0;
        char br = ' ';
        for(int i = 0; i < S.length(); i++){
            if (S.charAt(i) == br){
                current = 0;
            }else{
                current++;
            }
        }
        System.out.println(current);
    }
}

下面是我写的输出最长单词的长度

import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String S = in.nextLine();
      	int past = 0;
        int current = 0;
        char br = ' ';
        for(int i = 0; i<S.length();i++){
            if (S.charAt(i) == br){
                if (current>past){
                    past = current;
                }
                current = 0;
            }else{
                current++;
            }
        }
        System.out.println(current>past?current:past);
    }
}
全部评论
这个解法好聪明
点赞 回复 分享
发布于 2022-07-11 12:59
为什么类名为main
点赞 回复 分享
发布于 2022-02-10 12:02

相关推荐

牛客38347925...:9,2学生暑期实习失利开始投小厂,给这群人整自信了
点赞 评论 收藏
分享
qq乃乃好喝到咩噗茶:院校后面加上211标签,放大加粗,招呼语也写上211
点赞 评论 收藏
分享
把实习生当正职使昨天第一天就加班,晚上连口饭都没吃上,以后日子咋过,我不想干了
码农索隆:实习不怕忙,就怕干的活重复且没难度,要干就干那种有深度有难度的任务,这样才能快速的提升
实习吐槽大会
点赞 评论 收藏
分享
评论
1
2
分享

创作者周榜

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