【问题标题】:Finding the longest word ArrayList /Java查找最长的单词 ArrayList /Java
【发布时间】:2022-01-01 18:27:13
【问题描述】:

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

我使用了 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 ");


}

}

【问题讨论】:

标签: java arrays string if-statement arraylist


【解决方案1】:

事实是,在您迭代整个列表之前,您无法分辨出最大的词是什么。

所以迭代列表

  • 如果单词大于之前的最大大小:清除列表并保存单词
  • 如果单词的大小与最大大小相同:保存单词
  • 如果字更小:什么都没有
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]

【讨论】:

  • 可以在一个循环中完成。 int maxLength = 0; List&lt;String&gt; largestStrings = new ArrayList&lt;&gt;(); for (String s : wordsList) { if (s.length() &gt; maxLength) { maxLength = s.length(); largestStrings.clear(); largestStrings.add(s); } else if (s.length() == maxLength) { largestStrings.add(s); }}
【解决方案2】:

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;
    }
}

【讨论】:

    【解决方案3】:

    您可以通过一次循环迭代来做到这一点。随时存储最长的单词。

    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);
        }
    }
    

    【讨论】:

      【解决方案4】:

      我的两分钱让它在一个循环中完成。可以进一步改进。

      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);
      

      【讨论】:

        【解决方案5】:

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

        • 遍历单词
        • 如果当前字长为&gt; 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]
        

        【讨论】:

          【解决方案6】:

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

          第一个解决方案:

          `

          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();
              }
          
          }
          

          `

          【讨论】:

          • 比较函数可以简化为return a1.length() - b1.length();
          • 你是对的(我在编码方面很烂)!感谢您的评论,我已经编辑了我的代码。 @RotoRa
          猜你喜欢
          • 1970-01-01
          • 2014-09-26
          • 1970-01-01
          • 1970-01-01
          • 2018-09-28
          • 2013-04-28
          • 2023-04-08
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多