Leetcode 14. Longest Common Prefix

来源:互联网 发布:剑网3莫雨捏脸数据 编辑:程序博客网 时间:2024/06/07 08:30

题目:

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);    }};
原创粉丝点击