【问题标题】:Return the longest word in a string返回字符串中最长的单词
【发布时间】:2020-03-04 17:54:12
【问题描述】:

好的,首先,请不要将此标记为重复的问题。我知道有类似的问题可以用特定的字符串来解释它,可以这么说,我需要一个“通用代码”。我知道如何使用给定的数组执行此操作,但我不确定如何执行此分配。它希望我返回一个不存在的数组中最长的单词。但是,例如,如果有一个 ["dog", "ostrich", "eagle"] 数组,它将返回 "ostrich"

public class Longest {
    public static String longWord(String[] word) {
        int array[] = [];
        for (int i = 0; i < array.length; i++) {
            if (word > current) {
                return longWord;
            }
        }
    }
}

【问题讨论】:

    标签: java arrays string recursion max


    【解决方案1】:

    您可以为此使用Stream.max(Comparator) 方法:

    String[] arr = {"dog", "ostrich", "eagle"};
    
    String max = Arrays.stream(arr)
            .max(Comparator.comparingInt(String::length))
            .orElse(null);
    
    System.out.println(max); // ostrich
    

    另见:First unique character in a string using LinkedHashMap

    【讨论】:

      【解决方案2】:

      遍历单词,如果当前单词的长度比前一个单词长,则将最长的单词作为当前单词。所以最后你会得到最长的单词。

      public class Longest {
          public static String longWord(String[] words) {
              //assume initially the longest word is an empty String
              String longestWord = "";
              //loop through each word
              for (String word: words) {
                  //check if the each items length with previous largest length
                  if (word.length() > longestWord.length()) {
                      //make longest word as current if it matches the condition
                      longestWord = word;
                  }
              }
              //return the longest word,if word array is empty it return empty String
              return longestWord;
          }
      }
      

      或者使用数组排序的方法,找到最大的元素如下

      public class Longest {
          public static String longWord(String[] word) {
              //sort the array based on the length,So that
              // largest element will be at the end of the array
              Arrays.sort(word, Comparator.comparing(String::length));
              //return the last element
              return word[word.length-1];
          }
      }
      

      【讨论】:

        【解决方案3】:

        首先找到字符串数组的长度,然后使用strlen() 循环查找每个单词的长度。保留两个变量,一个为最大长度,一个为最长字符串的索引,返回str[index]

        【讨论】:

          猜你喜欢
          • 2014-10-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-01
          • 2016-06-29
          • 1970-01-01
          • 2018-04-18
          相关资源
          最近更新 更多