【Lintcode】133. Longest Word

題目地址:

https://www.lintcode.com/problem/longest-word/description

給定一個字符串數組,返回其所有長度最長的字符串。

思路是用一個列表維護已經發現的所有長度最長的字符串,當遇到新的字符串比列表中字符串還要長的時候,就將列表清空後把新的字符串加進去;如果新的字符串和列表中已有的字符串一樣長,說明這個字符串也是已經發現的最長的字符串之一,將其加入列表;否則如果新的字符串長度不及列表中的字符串,直接跳過。代碼如下:

import java.util.ArrayList;
import java.util.List;

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> res = new ArrayList<>();
        for (String s : dictionary) {
            if (res.isEmpty()) {
                res.add(s);
            } else if (s.length() > res.get(0).length()) {
                res.clear();
                res.add(s);
            } else if (s.length() == res.get(0).length()) {
                res.add(s);
            }
        }
        
        return res;
    }
}

時間複雜度O(n)O(n),空間O(1)O(1)(不包括返回的結果)。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章