资讯专栏INFORMATION COLUMN

[LintCode] Longest Words

roadtogeek / 3048人阅读

Problem

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?

Solution
class Solution {
    ArrayList longestWords(String[] dictionary) {
        // write your code here
        ArrayList res = new ArrayList();
        for (String word: dictionary) {
            if (res.isEmpty() || res.get(0).length() < word.length()) {
                res.clear();
                res.add(word);
            }
            else if (res.get(0).length() == word.length()) res.add(word);
            else continue;
        }
        return res;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/65506.html

相关文章

  • [LintCode/LeetCode] Longest Palindrome Substring

    摘要:是左闭右开区间,所以要。,要理解是和之间只有一个元素。循环每次的时候,都要更新子串更大的情况。补一种中点延展的方法循环字符串的每个字符,以该字符为中心,若两边为回文,则向两边继续延展。循环返回长度最长的回文串即可。 Problem Given a string S, find the longest palindromic substring in S. You may assume ...

    AaronYuan 评论0 收藏0
  • [LintCode] Longest Substring Without Repeating Cha

    摘要:哈希表法双指针法只有当也就是时上面的循环才会结束,,跳过这个之前的重复字符再将置为 Problem Given a string, find the length of the longest substring without repeating characters. Example For example, the longest substring without repeat...

    Scliang 评论0 收藏0
  • [LintCode] Longest Palindrome

    Problem Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters. This is case sensitive, for example Aa is not ...

    nicercode 评论0 收藏0
  • [LintCode] Longest Increasing Subsequence

    Problem Given a sequence of integers, find the longest increasing subsequence (LIS). You code should return the length of the LIS. Clarification Whats the definition of longest increasing subsequence?...

    Flands 评论0 收藏0
  • [LintCode] Longest Repeating Subsequence

    摘要:用二维数组进行动态规划,作为第位和的位已有的重复子序列长度最大值计数器。 Problem Given a string, find length of the longest repeating subsequence such that the two subsequence don’t have same string character at same position, i.e...

    Karuru 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<