14. Longest Common Prefix

14. Longest Common Prefix

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

Analysis:
常规题,要细心。
单元测试:
空数组:{}
数组中出现空字符串:{"a" "" "b"}
数组中只有一个字符串。{"a"}

Source Code(C++):

#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        if (strs.empty()){
            return "";
        }
        if (strs.size() == 1){
            return strs.at(0);
        }
        string common_prefix = strs.at(0);  
        for(int i=1; i<strs.size(); i++) {          
            if (common_prefix == "") {
                return "";
            }
            int j=0;
            string temp_prefix;
            while(j<common_prefix.size() && j<strs.at(i).size() && common_prefix.at(j) == strs.at(i).at(j)) {  //注意&&运行为从左到右运行的,判断尺寸必须放在前边
                temp_prefix.push_back(common_prefix.at(j));
                j++;
            }
            common_prefix = temp_prefix;        
        }
        return common_prefix;
    }
};

int main() {
    Solution sol;
    vector<string> v;
    v.push_back("c");
    v.push_back("c");
    cout << sol.longestCommonPrefix(v);
    return 0;
}

你可能感兴趣的:(14. Longest Common Prefix)