14. Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Note:

All given inputs are in lowercase letters a-z

algorithm thought

以第一个字符串为基准,从第一个字符开始,对比所有字符串。出现不一样的就返回,都是一样的就加入到返回值后面。

code

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        if(strs.size()==1)
            return strs[0];
        if(strs.size()==0)
            return "";
        string res="";
        for(int i=0;i<strs[0].size();++i){
            for(int j=1;j<strs.size();++j){
                if(i==strs[j].size()||strs[0][i]!=strs[j][i]){
                    return res;
                }
            }
            res.push_back(strs[0][i]);
        }
        return res;
    }
};

algorithm analysis

其实整个算法的逻辑是不需要判断size==1的,也就是第一行。但是如果不判断的话,就会在循环中一直判断并且调用push_back到res中,会及其耗时间。加上第一个判断之后,整个代码运行时会快很多的。

Last updated