leetcode 14. Longest Common Prefix

来源:互联网 发布:linux vi退出命令 编辑:程序博客网 时间:2024/05/20 11:26

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 "";int minlen = strs[0].length();for (int i = 1; i < strs.size(); i++)if (strs[i].length() < minlen)minlen = strs[i].length();string cp = string(strs[0].begin(), strs[0].begin() + minlen);for (int i = 1; i < strs.size(); i++){int k = 0;while (k < cp.length() && string(cp.begin(), cp.begin() + cp.length() - k) !=string(strs[i].begin(), strs[i].begin() + cp.length() - k))k++;if (k == cp.length())return "";cp = string(cp.begin(), cp.begin() + cp.length() - k);}return cp;}};

accept

0 0