[LeetCode] Longest Common Prefix

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

题目言简意赅,貌似也不难,暴力法用一个char *数组存放strs里每个元素的起始地址,然后循环,同时把所有指针向前移动,

如果有其中有一个字符失配就算完成,写的时候出现一个bug就是在移动指针的时候没有判断是否超出了那个string的长度,导致莫名其妙的问题。

string longestCommonPrefix(vector<string> &strs) {
    if (strs.size() == 0) return string();
    if (strs.size() == 1) return strs[0];
    char *ptrs[strs.size()];
    for (int i = 0; i < strs.size(); i++) {
        ptrs[i] = &(strs[i][0]);
    }
    
    bool failed = false;
    int bias = 0;
    int i;
    string res;
    while (!failed){
        for (i = 1; i < strs.size(); i++) {
            if ((bias >= strs[i].size() || bias >= strs[i-1].size()) || *(ptrs[i]+bias) != *(ptrs[i-1]+bias)){
                failed = true;
                break;
            }
        }
        if (!failed){
            res += strs[0][bias];
            bias++;
        }
    }
    
    return res;
}
原文地址:https://www.cnblogs.com/agentgamer/p/4049596.html