[LeetCode] Longest Common Prefix

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

找出字符串数组中最长的公共前缀。

思路:将字符串数组中每个字符串左对齐,排成一列,然后依次对比每个字符串的相同位置的字母。

如果不同则返回上一次对比相同的结果。

如果遇到最小长度的字符串,则返回上次对比相同的结果。

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        if (strs.empty())
            return "";
        string str;
        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 str;
            }
            str = str + c;
        }
        return str;
    }
};
// 6 ms

 

posted @ 2017-11-17 20:20  immjc  阅读(119)  评论(0编辑  收藏  举报