码迷,mamicode.com
首页 > 其他好文 > 详细

Longest Words

时间:2016-07-10 07:36:42      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:

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"].

分析:

因为要保持所有的最长string,所以我们可以用ARRAYLIST。如果arraylist为空,直接加进去,否则我们得把新的字符串和arraylist里面的字符串进行比较。如果小于arraylist里面的字符串,do nothing, 如果相等,则加进去,如果大于,则清空arraylist,然后把该字符串加进去。

 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         if (dictionary == null || dictionary.length == 0)
 8             return null;
 9         ArrayList<String> list = new ArrayList<String>();
10 
11         for (String str : dictionary) {
12             if (list.size() == 0) {
13                 list.add(str);
14             } else if (list.get(0).length() < str.length()) {
15                 list.clear();
16                 list.add(str);
17             } else if (list.get(0).length() == str.length()) {
18                 list.add(str);
19             }
20         }
21         return list;
22     }
23 }

 

 

Longest Words

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5657058.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!