LintCode题解之最长单词

 

这些一次遍历搞定的,套路无非都是在遍历的时候就记录数据的状态,然后根据遍历到的当前的数据的状态来修改最终结果,当遍历完了的时候结果也就确定了。

public class Solution {
    
    /*
     * @param dictionary: an array of strings
     * @return: an arraylist of strings
     */
    public List<String> longestWords(String[] dictionary) {
        
        int maxLength = Integer.MIN_VALUE;
        List<String> resultList = new ArrayList<>();
        
        for(String s : dictionary){
            if(s.length()>maxLength){
                maxLength = s.length();
                resultList = new ArrayList<>();
                resultList.add(s);
            }else if(s.length()==maxLength){
                resultList.add(s);
            }
        }
        
        return resultList;
    }
    
}

 

题目来源: http://www.lintcode.com/zh-cn/problem/longest-words/

原文地址:https://www.cnblogs.com/cc11001100/p/7898183.html