给一个词典,找出其中所有最长的单词。

题目

描述
给一个词典,找出其中所有最长的单词。

您在真实的面试中是否遇到过这个题?
样例
在词典

{
“dog”,
“google”,
“facebook”,
“internationalization”,
“blabla”
}
中, 最长的单词集合为 [“internationalization”]

在词典

{
“like”,
“love”,
“hate”,
“yes”
}
中,最长的单词集合为 [“like”, “love”, “hate”]

挑战
遍历两次的办法很容易想到,如果只遍历一次你有没有什么好办法?

解答

只需要遍历一次

public class LongestWord {
    /*
     * @param dictionary: an array of strings
     * @return: an arraylist of strings
     */
    public List<String> longestWords(String[] dictionary) {
        // write your code here
        int maxLength = 0;
        Map<Integer, List<String>> countMap = new HashMap<Integer, List<String>>();
        for (int i = 0; i < dictionary.length; i++) {
            // 保存最大长度值
            if (dictionary[i].length() > maxLength) {
                maxLength = dictionary[i].length();
            }
            // 按照长度保存为list
            if (countMap.get(dictionary[i].length()) == null) {
                List countList = new ArrayList();
                countList.add(dictionary[i]);
                countMap.put(dictionary[i].length(), countList);
            } else {
                List countList = countMap.get(dictionary[i].length());
                countList.add(dictionary[i]);
            }
        }
        return countMap.get(maxLength);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值