lintcode-easy-Longest Words

本文介绍了一种算法,该算法能从给定的字符串数组中找出所有最长的单词,并将其返回。通过一次遍历即可完成任务,提高了效率。

Given a dictionary, find all of the longest words in the dictionary.

Example

Given

{
  "dog",
  "google",
  "facebook",
  "internationalization",
  "blabla"
}

the longest words are(is) ["internationalization"].

Given

{
  "like",
  "love",
  "hate",
  "yes"
}

the longest words are ["like", "love", "hate"].

Challenge

It's easy to solve it in two passes, can you do it in one pass?

 

class Solution {
    /**
     * @param dictionary: an array of strings
     * @return: an arraylist of strings
     */
    ArrayList<String> longestWords(String[] dictionary) {
        // write your code here
        ArrayList<String> result = new ArrayList<String>();
        
        if(dictionary == null || dictionary.length == 0)
            return result;
        
        for(int i = 0; i < dictionary.length; i++){
            if(result.size() == 0)
                result.add(dictionary[i]);
            else{
                if(dictionary[i].length() > result.get(result.size() - 1).length()){
                    result = new ArrayList<String>();
                    result.add(dictionary[i]);
                }
                else if(dictionary[i].length() == result.get(result.size() - 1).length()){
                    result.add(dictionary[i]);
                }
            }
        }
        
        return result;
    }
};

 

转载于:https://www.cnblogs.com/goblinengineer/p/5219156.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值