Lintcode:最长单词

    xiaoxiao2023-11-19  152

    问题:

    给一个词典,找出其中所有最长的单词。

    样例:

    样例 1: 输入: { "dog", "google", "facebook", "internationalization", "blabla" } 输出: ["internationalization"] 样例 2: 输入: { "like", "love", "hate", "yes" } 输出: ["like", "love", "hate"]

    python:

    class Solution: """ @param: dictionary: an array of strings @return: an arraylist of strings """ def longestWords(self, dictionary): # write your code here dictlen = len(dictionary) result = [] if dictlen == 0: return result strlen = len(dictionary[0]) result.append(dictionary[0]) for i in range(1,dictlen): temp = dictionary[i] if strlen == len(temp): result.append(temp) elif strlen < len(temp): result = [] strlen = len(temp) result.append(temp) return result

    C++:

    class Solution { public: /* * @param dictionary: an array of strings * @return: an arraylist of strings */ vector<string> longestWords(vector<string> &dictionary) { // write your code here vector<string> result; int strNum=dictionary.size(); if(strNum==0) { return result; } int maxLen=dictionary[0].size(); result.push_back(dictionary[0]); for(int i=1; i < strNum; i++) { int tempLen = dictionary[i].size(); if(maxLen == tempLen) { result.push_back(dictionary[i]); } else if(maxLen < tempLen) { maxLen = tempLen; vector<string>().swap(result); result.push_back(dictionary[i]); } } return result; } };

     

     

    最新回复(0)