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

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

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);
    }
}
全部评论
为什么类名为main
点赞
送花
回复 分享
发布于 2022-02-10 12:02
这个解法好聪明
点赞
送花
回复 分享
发布于 2022-07-11 12:59
秋招专场
校招火热招聘中
官网直投

相关推荐

1 2 评论
分享
牛客网
牛客企业服务