[LeetCode] Longest Common Prefix

2014-11-24 01:44:09 · 作者: · 浏览: 1
Write a function to find the longest common prefix string amongst an array of strings.
问题描述:写一个函数找到一组字符串的最长公共前缀。
这个题要明确一个观点,一组字符串的最长公共前缀不会比该组字符串中任意两个字符串的公共前缀还长,那么,就可以遍历字符串数组,求出遍历字符串与已得到的公共前缀的公共前缀,遍历完的结果就是该字符串数组的最长公共前缀。
class Solution {  
public:  
    string strprefix(string str1, string str2)  
    {  
        int i = 0;  
        string str;  
  
        while(i < str1.size() && i < str2.size() && str1.at(i) == str2.at(i)) {  
            str += str1.at(i);  
            ++i;  
        }  
  
        return str;  
    }  
  
    string longestCommonPrefix(vector
&strs) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if(strs.size() == 0) return string(); string str = strs[0]; for(vector::iterator iter = strs.begin(); iter != strs.end(); ++iter) { str = strprefix(str, *iter); } return str; } };