外国编程挑战网站: https://coderbyte.com/editor/guest:Longest%20Word:Java
上面的题,题目如下
Using the Java language, have the function LongestWord(sen) take the sen parameter being passed and return the largest word in the string. If there are two or more words that are the same length, return the first word from the string with that length. Ignore punctuation and assume sen will not be empty.
我使用 java 编程,几本思想是:首先将字符串中的各个单词挑出来存在一个数组里,然后比较每个单词的长度,从中选出最长的单词。
不使用 stream:
import java.util.ArrayList;
import java.util.Scanner;
public class LongestWord {
public static void main(String[] args) {
System.out.println("please input some words:");
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
ArrayList<String> strArray = new ArrayList<>();
int longWordIndex = -1;
int strLength = 0;
String tempStr = "";
for (int i = 0; i<str.length(); i++) {
if ((str.charAt(i) >= 'a' && str.charAt(i) <='z') || (str.charAt(i) >= 'A' && str.charAt(i) <='Z')) {
tempStr = tempStr + str.charAt(i);
if (i == str.length() - 1) {
strArray.add(tempStr);
if (tempStr.length() > strLength){
strLength = tempStr.length(); longWordIndex++;
}
}
}
else
{
if (tempStr != "") {
strArray.add(tempStr);
if (tempStr.length() > strLength){
strLength = tempStr.length(); longWordIndex++;
}
}
tempStr = "";
}
}
scan.close();
System.out.println(strArray.get(longWordIndex));
}
}
使用 stream 里面的 maxBy:
import java.util.ArrayList;
import java.util.Optional;
import java.util.Scanner;
import java.util.stream.Collectors;
public class LongestWord {
public static void main(String[] args) {
System.out.println("please input some words:");
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
ArrayList<String> strArray = new ArrayList<>();
int strLength = 0;
String tempStr = "";
for (int i = 0; i<str.length(); i++) {
if ((str.charAt(i) >= 'a' && str.charAt(i) <='z') || (str.charAt(i) >= 'A' && str.charAt(i) <='Z')) {
tempStr = tempStr + str.charAt(i);
if (i == str.length() - 1)
strArray.add(tempStr);
}
else
{
if (tempStr != "")
strArray.add(tempStr);
tempStr = "";
}
}
scan.close();
Optional<String> longWord = strArray.stream().collect(Collectors.maxBy((s1, s2) -> s1.length() - s2.length()));
System.out.println(longWord.get());
}
}
更简单的:用 replaceAll 来分解字符串
import java.util.Optional;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class LongestWord {
public static void main(String[] args) {
System.out.println("please input some words:");
Scanner scan = new Scanner(System.in);
String sen = scan.nextLine();
String[] strArray = sen.replaceAll("[^a-zA-Z]", " ").split(" ");
Optional<String> longWord = Stream.of(strArray).collect(Collectors.maxBy((s1, s2) -> s1.length() - s2.length()));
scan.close();
System.out.println(longWord.get());
}
}