4 回答

TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超5個(gè)贊
您可以使用模運(yùn)算符 () 來檢查字符串長度是否為偶數(shù):%
string.length() % 2 == 0
為此,您可以使用 Arrays.stream() 來查找長度為偶數(shù)的最長字符串:
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貢獻(xiàn)1775條經(jīng)驗(yàn) 獲得超8個(gè)贊
更改是您比較最長長度的>,而不是>=并檢查長度是否均勻。
要適應(yīng)存在其他符號(hào)(如 '.')的情況,請使用正則表達(dá)式模式。
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);
}
這將打印出最大的第一個(gè)偶數(shù)字

TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超8個(gè)贊
在python中這個(gè)問題的解決方案是:
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貢獻(xiàn)1909條經(jīng)驗(yàn) 獲得超7個(gè)贊
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;
}
}
添加回答
舉報(bào)