Refer to the test below, some test cases are failed in fact even the output is correct. Can anyone advise?
https://coderbyte.com/editor/Longest%20Word:Java
Longest Word 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. Examples
Input: "fun&!! time"
Output: time
Input: "I love dogs"
Output: love
Below are the invalid failing test cases
-
For input "a beautiful sentence^&!" the output was incorrect. The correct output is beautiful
-
For input "oxford press" the output was incorrect. The correct output is oxford
-
For input "123456789 98765432" the output was incorrect. The correct output is 123456789
-
For input "a b c dee" the output was incorrect. The correct output is dee
-
For input "a confusing /:sentence:/[ this is not!!!!!!!~" the output was incorrect. The correct output is confusing
The program
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Main {
public static final String REG_EXP_CHAR_ONLY = "(?=.*?[a-zA-Z0-9 ])";
public static String LongestWord(String sen) {
StringBuffer strBuffer = new StringBuffer();
for (String c : sen.split("")) {
//System.out.println("c--------->" + c);
if (isValid(c)) {
strBuffer.append(c);
}
}
//System.out.println(strBuffer.toString());
String longest = Arrays.stream(strBuffer.toString().split(" ")).max(Comparator.comparingInt(String::length))
.orElse(null);
return longest;
}
public static boolean isValid(String c) {
// System.out.println("char -->" + c);
Pattern pattern = Pattern.compile(REG_EXP_CHAR_ONLY);
Matcher matcher = pattern.matcher(c);
boolean matchFound = matcher.find();
if (matchFound) {
// System.out.println("Match found");
return true;
}
return false;
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(LongestWord(s.nextLine()));
}
}
Aucun commentaire:
Enregistrer un commentaire