【Longest Common Prefix】cpp

题目:

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

代码:

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
            if ( strs.size()==0 ) return "";
            std::string tmp_str = strs[0];
            for ( size_t i = 1; i < strs.size(); ++i )
            {
                size_t j = 0;
                for ( ; j < std::min(tmp_str.size(), strs[i].size()); ++j ) 
                    if ( tmp_str[j]!=strs[i][j] ) break;
                tmp_str = tmp_str.substr(0,j);
            }
            return tmp_str;
    }
};

tips:

空间复杂度O(n1),时间复杂度O(n1+n2...)

strs中的每个string串依次两两比较,保留下这一次比较得出的公共前缀为tmp_str;下次再比较时,可以用上次得到的公共前缀作为目标字符串。

这个解法的好处就是代码比较consice,但空间复杂度和时间复杂度其实都不是最优的。

=====================================================

第二次过这道题,自己写出来了代码,调了两次AC了。

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
            if ( strs.size()==0 ) return "";
            if ( strs.size()==1 ) return strs[0];
            string common_pre = strs[0];
            for ( int i=1; i<strs.size(); ++i )
            {
                if ( common_pre.size()==0 ) break;
                int common_len = min( common_pre.size(), strs[i].size());
                for ( int j=0 ;j<min( common_pre.size(), strs[i].size()); ++j )
                {
                    if ( common_pre[j]!=strs[i][j] )
                    {
                        common_len = j;
                        break;
                    }
                }
                common_pre = common_pre.substr(0,common_len);
            }
            return common_pre;
    }
};
原文地址:https://www.cnblogs.com/xbf9xbf/p/4492704.html