4 回答
TA贡献1856条经验 获得超5个赞
您可以使用模运算符 () 来检查字符串长度是否为偶数:%
string.length() % 2 == 0
为此,您可以使用 Arrays.stream() 来查找长度为偶数的最长字符串:
String longestWord = Arrays.stream(sentence.split(" ")) // creates the stream with words
.filter(s -> s.length() % 2 == 0) // filters only the even length strings
.max(Comparator.comparingInt(String::length)) // finds the string with the max length
.orElse(" "); // returns " " if none string is found
TA贡献1775条经验 获得超8个赞
更改是您比较最长长度的>,而不是>=并检查长度是否均匀。
要适应存在其他符号(如 '.')的情况,请使用正则表达式模式。
public static void main(String[] args) {
// TODO Auto-generated method stub
String input = "I am good.";
String[] input_words = input.split(" ");
String longestWord = " ";
for(String word : input_words) {
Pattern p = Pattern.compile("^[a-zA-Z]+");
Matcher m = p.matcher(word);
m.find();
if(m.group().length() % 2 == 0 && m.group().length() > longestWord.length()) {
longestWord = m.group();
}
}
System.out.println("result : " + longestWord);
}
这将打印出最大的第一个偶数字
TA贡献1860条经验 获得超8个赞
在python中这个问题的解决方案是:
def longestevenword(sentence):
#converting the sentence into lists
string_list = sentence.split()
size = 0
#iteration through each word in the list
for word in string_list:
#check to see if the word has even number of characters
if len(word)%2 == 0:
#checking if the length of the of the word
if size <= len(word):
size = len(word)
even_word = word
else:
continue
# printing the longest even word in a given sentence.
print(even_word)
## function call to test
longestevenword("This is a cat that had a puppyy")
Output: puppyy
它也可以在我的GitHub https://github.com/jaikishpai/CommonSolutions/blob/main/LongestEvenWord.py
TA贡献1909条经验 获得超7个赞
public class LongestEvenString {
public static void main(String[] args) {
String test = "this is a sample input for the problem";
System.out.println(longestEvenString(test));
}
public static String longestEvenString(String test) {
// Splits a sentence to array of Strings.
String[] words = test.split(" ");
// curlen stores length of current word in string Array
// maxlen stores length of maximum_length word in string Array
int curlen = 0;
int maxlen = 0;
String output = "";
for (String word:words) {
curlen = word.length();
// loop runs only if length of the current word is more than
// maximum_length thus excluding future same maximum_length words.
// and also checks for even_length of that word
if(curlen > maxlen && curlen%2 == 0){
maxlen = curlen;
output = word;
}
}
// returns maximum_even_length word which occurred first
return output;
}
}
添加回答
举报