【Leetcode】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.

思路一

最朴素的想法,竖直扫描,将所有字符串的第一位进行比较,再将所有字符串的第二位进行比较,直到找到最长的前缀

时间复杂度:若共有m个字符串,每个字符串长n,最差的情况是所有字符串相同,则要比较O(mn);若有字符串不同,则较好情况比较O(m*minLen),minLen是字符串中长度最短的。

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        if(strs.size() == 0)
            return "";
        string res="";
        int min_len = INT_MAX;
        for(int i = 0; i < strs.size(); i++)
            min_len= (min_len > strs[i].size()?strs[i].size():min_len);
        // 拿str[0][i]和 所有的str[j][i] j>1 一位位比较 
        for(int i = 0; i < min_len; i++)
        {
            bool flag=true;
            char x = strs[0][i];
            // 注意新的写法C++11
            for(auto& s:strs)  
            {
                if(s[i]!=x)
                {
                    flag=false;
                    break;
                }
            }
            if(flag == false)
                return res;
            res += x;
        }
        return res;
    }
};

 

思路二

水平扫描

时间复杂度:最差也是一样,所有字符串都相同,O(mn)

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        if(strs.size()==0)
            return "";
        string ans=strs[0];  
        for(auto& s:strs)
        {
            if(s.length() == 0)
                return "";
            int i=0;
            for(i = 0; i < ans.length() && i < s.length(); i++)
            {
                if(s[i]!=ans[i])
                    break;
            }
            ans=ans.substr(0,i);
        }

        return ans;
    }
};

 

思路三

二分查找的思想

先找一个按ACSII排最大的字符串L,把它作为公共前缀。然后找到所有字符串中的最短长度minLen。

 

思路四

字典树

 

posted @ 2018-07-28 14:25  Heisenber9  阅读(131)  评论(0编辑  收藏  举报