11_leetcode_Longest Common Prefix

来源:互联网 发布:无线互动课堂教学软件 编辑:程序博客网 时间:2024/05/14 19:05

Write a function to find the longest common prefix string amongst an array of strings.

1.考虑字符数组是空或者只有一个字符串的情况;2.找到第一个字符串与其他所有字符串的公共长度的最小值;

   

 string longestCommonPrefix(vector<string> &str)    {        if(str.empty())            return "";        if(str.size() == 1)            return str[0];                int minLength = (int)str[0].size();        for(int i = 1; i < str.size(); i++)        {            int tempLength = lengthCommonPrefix(str[0], str[i]);            if(tempLength < minLength)            {                minLength = tempLength;            }        }                return str[0].substr(0, minLength);    }

0 0