算法提高 ADV-78 最长单词

来源:互联网 发布:精英特速读软件 编辑:程序博客网 时间:2024/06/07 17:47
编写一个函数,输入一行字符,将此字符串中最长的单词输出。
  输入仅一行,多个单词,每个单词间用一个空格隔开。单词仅由小写字母组成。所有单词的长度和不超过100000。如有多个最长单词,输出最先出现的。
样例输入
I am a student
样例输出
     student

import java.io.BufferedReader;import java.io.InputStreamReader;public class Main{public static void main(String[] args) throws Exception{BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in));String str = bfr.readLine();String max = "";String [] arr = null;while(str.contains(" ")){arr = str.split(" ");if (arr[0].length()>max.length()){max = arr[0];//System.out.println(max);}str = str.substring(arr[0].length()+1);//System.out.println(str);}if (arr[1].length()>max.length()){max = arr[1];}System.out.println(max);}}



原创粉丝点击