最长公共前缀 -LintCode

来源:互联网 发布:unity3d 角色动作 编辑:程序博客网 时间:2024/05/29 11:13

给k个字符串,求出他们的最长公共前缀(LCP)
样例
在 “ABCD” “ABEF” 和 “ACEF” 中, LCP 为 “A”
在 “ABCDEFG”, “ABCEFG”, “ABCEFA” 中, LCP 为 “ABC”

#ifndef C78_H#define C78_H#include<iostream>#include<vector>#include<string>using namespace std;class Solution {public:    string longestCommonPrefix(vector<string> &strs) {        // write your code here        int k = strs.size();        int minLength = INT_MAX;        int pos=0;        for (auto ss : strs)        {            if (ss.size() <= minLength)                minLength = ss.size();        }        for (int j = 0; j < k - 1; ++j)         {                for (int i = 0; i < minLength; ++i)                {                    if (strs[j][i] != strs[j + 1][i])                    {                        pos = i;         //相同的元素个数                        break;                    }                    if (i == minLength-1)                    {                        pos = minLength;//前缀是它本身                        break;                    }                }            }        string s(strs[0],0,pos);        return s;    }};#endif
原创粉丝点击