寻找最长的单词 ArrayList /Java

Finding the longest word ArrayList /Java

我想写一个方法来找到最长的字符串(单词)。如果两个词的长度相同,则输出应该是最长的词,输出应该是:“不止一个最长的词”。

我用的是ArrayList,差点就有解决办法了,但是出问题了。情况是当两个词的长度相同时我遇到了问题。 输出是: 不止一个最长的单词 不止一个最长的单词 14递增是最长的字

请检查我的一段代码并帮助我找到答案:)

public class LongestWord {
public static void main(String[] args) {


    ArrayList<String> wordsList = new ArrayList<String>();
    wordsList.add("december");
    wordsList.add("california");
    wordsList.add("cat");
    wordsList.add("implementation");
    wordsList.add("incrementation");


    int largestString = wordsList.get(0).length();
    int index = 0;

    for (int i = 0; i < wordsList.size(); i++) {
        if (wordsList.get(i).length() > largestString) {
            largestString = wordsList.get(i).length();
            index = i;

        }else if(wordsList.get(i).length() == largestString){
            largestString = wordsList.get(i).length();
            index = i;
            System.out.println("More than one longest word");
        }
    }
    System.out.println(largestString +" " + wordsList.get(index) +" is the longest word ");


}

}

事实是,在遍历整个列表之前,您无法判断最大的单词是什么。

所以在列表上迭代

  • 如果单词大于先前的最大大小:清除列表并保存单词
  • 如果单词的大小与最大大小相同:保存单词
  • 如果单词较小:无
List<String> wordsList = Arrays.asList(
        "december", "california", "cat",
        "implementation", "incremntation");

int maxLength = Integer.MIN_VALUE;

List<String> largestStrings = new ArrayList<>();
for (String s : wordsList) {
    if (s.length() > maxLength) {
        maxLength = s.length();
        largestStrings.clear();
        largestStrings.add(s);
    } else if (s.length() == maxLength) {
        largestStrings.add(s);
    }
}

if (largestStrings.size() > 1) {
    System.out.println("More than one longest word");
    System.out.println(largestStrings);
} else {
    System.out.println(largestStrings.get(0) + " is the longest word");
}

给予

More than one longest word
[implementation, incrementation]

azro 是对的。您可以使用两次迭代找出问题。我不确定,但下面的代码有效

for (int i = 0; i < wordsList.size(); i++) {
    if (wordsList.get(i).length() > largestString) {
        largestString = wordsList.get(i).length();
        index = i;
    }
}

for (int i = 0; i < wordsList.size(); i++) {
    if (wordsList.get(index).length() == wordsList.get(i).length()) {
        System.out.println("More than one longest word");
        break;
    }
}

您可以通过一次循环迭代来完成此操作。随时存储最长的单词。

import java.util.*;

public class Test {
    public static void main(String[] args) {
        final Collection<String> words = Arrays.asList(
                "december", "california", "cat",
                "implementation", "incrementation");

        final Collection<String> longestWords = findLongestWords(words);

        if (longestWords.size() == 1) {
            System.out.printf("The longest word is: %s\n", longestWords.iterator().next());
        } else if (longestWords.size() > 1) {
            System.out.printf("More than one longest word. The longest words are: %s\n", longestWords);
        }
    }

    private static final Collection<String> findLongestWords(final Collection<String> words) {
        // using a Set, so that duplicate words are stored only once.
        final Set<String> longestWords = new HashSet<>();

        // remember the current length of the longest word
        int lengthOfLongestWord = Integer.MIN_VALUE;

        // iterate over all the words
        for (final String word : words) {
            // the length of this word is longer than the previously though longest word. clear the list and update the longest length.
            if (word.length() > lengthOfLongestWord) {
                lengthOfLongestWord = word.length();
                longestWords.clear();
            }

            // the length of this word is currently though to be the longest word, add it to the Set.
            if (word.length() == lengthOfLongestWord) {
                longestWords.add(word);
            }
        }

        // return an unmodifiable Set containing the longest word(s)
        return Collections.unmodifiableSet(longestWords);
    }
}

我的两分钱是在单循环中完成的。可以进一步改进。

ArrayList<String> wordsList = new ArrayList<String>();
    wordsList.add("december");
    wordsList.add("california");
    wordsList.add("cat");
    wordsList.add("implementation");
    wordsList.add("incrementation");

    String result;
    int length = Integer.MIN_VALUE;
    Map<String,String> map = new HashMap<>();

    for(String word: wordsList){

        if(word.length() >= length) {
            length = word.length();

            if (map.containsKey(String.valueOf(word.length())) || map.containsKey( "X" + word.length())) {
                map.remove(String.valueOf(word.length()));
                map.put("X" + word.length(), word);
            } else {
                map.put(String.valueOf(word.length()), word);
            }

        }
    }

     result = map.get(String.valueOf(length)) == null ? "More than one longest word" :
             map.get(String.valueOf(length)) + " is the longest word";

    System.out.println(result);

我更改了您的代码以提出解决问题的不同方法。老实说,我希望你会发现它很有吸引力和帮助。 它有两种不同的方式,一种不关心找到超过一个最长的单词(它只标记第一个 - 但您可以根据需要更改它),另一种关心。

第一个解决方案:

`

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class LongestWord {
    public static void main(String[] args) {


        List<String> wordsList = new ArrayList<>();
        wordsList.add("december");
        wordsList.add("california");
        wordsList.add("cat");
        wordsList.add("implementation");
        wordsList.add("incrementation");

        wordsList.stream()
            .max(LongestWord::compare)
            .ifPresent(a -> System.out.println(a.toUpperCase() + " is the longest word with length of: " + a.length()));

}

    private static int compare(String a1, String b1) {
       return a1.length() - b1.length();
    }

}

`

第二种解决方案:

`

public class LongestWord {
    public static void main(String[] args) {


        List<String> wordsList = new ArrayList<>();
        wordsList.add("december");
        wordsList.add("california");
        wordsList.add("cat");
        wordsList.add("implementation");
        wordsList.add("incrementation");

        int max_length = wordsList.stream()
                .max(LongestWord::compare)
                .map(String::length).orElse(0);

        List<String> finalWordsList = wordsList.stream()
                .filter(word -> word.length() == max_length)
                .collect(Collectors.toList());

        if (finalWordsList.size() > 1) {
            System.out.println("More than one longest word");
        } else {
            System.out.println(finalWordsList.get(0) + " is the longest word");
        }

    }

    private static int compare(String a1, String b1) {
      return a1.length() - b1.length();
    }

}

`

这是一种方法。我正在使用一个集合来保存结果,因为没有理由包含重复的单词(如果它们存在的话)。

  • 遍历单词
  • 如果当前字长为> maxLength,清空集合并添加字,更新maxLength
  • 如果等于maxLength,就加上这个词。
List<String> wordsList = List.of("december", "implementation",
        "california", "cat", "incrementation");

int maxLength = Integer.MIN_VALUE;
Set<String> results = new HashSet<>();
for (String word : wordsList) {
    int len = word.length();
    if (len >= maxLength) {
        if (len > maxLength) {
              results.clear();
              maxLength = len;
        }
        results.add(word);
    } 
}

System.out.printf("The longest word%s -> %s%n", results.size() > 1 ? "s" : "", results);

打印

The longest words -> [implementation, incrementation]