14. Longest Common Prefix

description:

Write a function to find the longest common prefix string amongst an array of strings.
找到几个字符串的最大前缀,英语不好是硬伤gg
prefix string 前缀!!!!!

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

Note:

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.

my answer:

感恩

把所有的字符串一行一行的排好,然后从第一列开始一列一列的去遍历,如果这一列全都相同就把这个character加入到result中,若出现不一样的或者有的字符串在这一列已经是空了就return result。

大佬的answer:

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

relative point get√:

hint :

原文地址:https://www.cnblogs.com/forPrometheus-jun/p/10625405.html