14. Longest Common Prefix 最长共同前缀

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

Difficulty: Easy

可以把输入的字符串数组,看成一个char的二维数组,定义指针i,j分别代表行数和列数,逐列查找,如果char[i][j]不等于char[0][j]或者第i个字符串的长度小于j就可以返回之前的结果了.

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 += c;
        }
        return res;
    }
};
 
comments powered by Disqus