蓝桥杯 算法提高 最长单词



import java.util.Scanner;

/**
 * <pre>
 *
 算法提高 最长单词
 时间限制:1.0s   内存限制:512.0MB

   编写一个函数,输入一行字符,将此字符串中最长的单词输出。
   输入仅一行,多个单词,每个单词间用一个空格隔开。单词仅由小写字母组成。所有单词的长度和不超过100000。如有多个最长单词,输出
 最先出现的。
 样例输入
 I am a student
 样例输出
 student
 <pre>
 */
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String line = sc.nextLine();
        String[] words = line.split(" ");

        int len = -1;
        int index = 0;

        for (int i=0; i<words.length; i++) {
            if (words[i].length() > len) {
                len = words[i].length();
                index = i;
            }
        }
        System.out.println(words[index]);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_35040169/article/details/79719663