Leetcode 14. 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) {
        int size = strs.size();
        if(size == 0) return "";
        int count = strs[0].length();
        for(int i = 1; i < size; ++i) {
            int temp = 0;
            while(temp < count && temp < strs[i].length() && strs[i][temp] == strs[0][temp]) temp++;
            count = temp<count?temp:count;
        }
        return strs[0].substr(0,count);
    }
};
posted on 2017-06-12 14:31  lantx  阅读(82)  评论(0编辑  收藏  举报