算法训练 最长字符串
时间限制:1.0s 内存限制:512.0MB
求出5个字符串中最长的字符串。每个字符串长度在100以内,且全为小写字母。
样例输入
one two three four five
样例输出
three
package lqtest;
import java.util.Scanner;
public class LongestString {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
String a[]=s.split(" ");
sc.close();
String max=null;
for(int i=0;i<a.length-1;i++)
{
if(a[i].length()>a[i+1].length())
{
max=a[i];
}
else
{
max=a[i+1];
}
}
System.out.println(max);
}
}
本文介绍了一个简单的算法挑战,即从五个字符串中找出最长的一个。通过Java代码示例,展示了如何读取输入并使用split方法分割字符串,然后遍历数组比较每个元素的长度来找到最长的字符串。
651





