Longest Words

Question

  1. Given a dictionary, find all of the longest words in the dictionary.
  2. Example
  3. Given
  4. {
  5. "dog",
  6. "google",
  7. "facebook",
  8. "internationalization",
  9. "blabla"
  10. }
  11. the longest words are(is) ["internationalization"].
  12. Given
  13. {
  14. "like",
  15. "love",
  16. "hate",
  17. "yes"
  18. }
  19. the longest words are ["like", "love", "hate"].
  20. Challenge
  21. It's easy to solve it in two passes, can you do it in one pass?

题解

简单题,容易想到的是首先遍历以便,找到最长的字符串,第二次遍历时取最长的放到最终结果中。但是如果只能进行一次遍历呢?一次遍历意味着需要维护当前遍历的最长字符串,这必然有比较与更新删除操作,这种情况下使用双端队列最为合适,这道题稍微特殊一点,不必从尾端插入,只需在遍历时若发现比数组中最长的元素还长时删除整个列表。

Java

  1. class Solution {
  2. /**
  3. * @param dictionary: an array of strings
  4. * @return: an arraylist of strings
  5. */
  6. ArrayList<String> longestWords(String[] dictionary) {
  7. ArrayList<String> result = new ArrayList<String>();
  8. if (dictionary == null || dictionary.length == 0) return result;
  9. for (String str : dictionary) {
  10. // combine empty and shorter length
  11. if (result.isEmpty() || str.length() > result.get(0).length()) {
  12. result.clear();
  13. result.add(str);
  14. } else if (str.length() == result.get(0).length()) {
  15. result.add(str);
  16. }
  17. }
  18. return result;
  19. }
  20. }

源码分析

熟悉变长数组的常用操作。

复杂度分析

时间复杂度 O(n), 最坏情况下需要保存 n - 1个字符串,空间复杂度 O(n).

Reference