给一个词典,找出其中所有最长的单词。
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 resultC++:
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; } };