【算法】【线性表】【数组】最长单词
1 题目
给一个词典,找出其中所有最长的单词。
样例 1:
输入: {
"dog",
"google",
"facebook",
"internationalization",
"blabla"
}
输出: ["internationalization"]
样例 2:
输入: {
"like",
"love",
"hate",
"yes"
}
输出: ["like", "love", "hate"]
2 解答
public class Solution { /* * @param dictionary: an array of strings * @return: an arraylist of strings */ public List<String> longestWords(String[] dictionary) { // write your code here List<String> resList = new ArrayList<>(); if (dictionary == null || dictionary.length == 0) { return resList; } int maxLen = dictionary[0].length(); resList.add(dictionary[0]); for (int i=1; i<dictionary.length; i++) { String str = dictionary[i]; if (str.length() < maxLen) continue; if (str.length() == maxLen) { resList.add(str); continue; } maxLen = str.length(); resList.clear(); resList.add(str); } return resList; } }
加油