lintcode: Longest Common Prefix

来源:互联网 发布:淘宝查小号信誉 编辑:程序博客网 时间:2024/06/08 10:12

 Longest Common Prefix

Given k strings, find the longest common prefix (LCP).

Example

For strings "ABCD""ABEF" and "ACEF", the LCP is "A"

For strings "ABCDEFG""ABCEFG" and "ABCEFA", the LCP is "ABC"

Tags 

class Solution {public:        /**     * @param strs: A list of strings     * @return: The longest common prefix     */    string longestCommonPrefix(vector<string> &strs) {        // write your code here                if (strs.size() == 0)            return ""; // 这个条件判断非常重要                int compLen = INT_MAX;        for (int i=0; i<strs.size(); i++)            compLen = min((int)strs[i].size(), compLen);                    string retStr = "";        for (int j=0; j<compLen; j++)        {            char pivot = strs[0][j];            for (int i=1; i<strs.size(); i++)            {                if (strs[i][j] != pivot)                {                    if (j > 0)                    {                        return strs[i].substr(0, j);                    }                    else                    {                        return "";                    }                }            }        }        return strs[0].substr(0, compLen);    }};





0 0
原创粉丝点击