Lintcode:最长单词

版权声明:本文未经博主允许不得转载。 https://blog.csdn.net/pianzang5201/article/details/90551360

问题:

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

样例:

样例 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;
    }
};

猜你喜欢

转载自blog.csdn.net/pianzang5201/article/details/90551360
今日推荐