首页 > 代码库 > 【LeetCode】Longest Common Prefix

【LeetCode】Longest Common Prefix

Longest Common Prefix

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

 

思路:设置一个位数记录器num,遍历所有字符串的第num位。如果都相同,则num++。

直到某字符串结束或者所有字符串的第num位不都相同,则返回[0~num-1]位,即最长公共前缀。

 

class Solution {public:    string longestCommonPrefix(vector<string> &strs) {        if(strs.empty())            return "";    //这边要注意,string是类不是指针,所以不是NULL        else if(strs.size() == 1)            return strs[0];        else        {            string ret = "";            int num = 0;            char c = strs[0][num];            while(true)            {                for(vector<string>::size_type st = 0; st < strs.size(); st ++)                {                    if(num < strs[st].size() && strs[st][num] == c)                    {//match                        if(st == strs.size()-1)                        {//end                            ret += c;                            num ++;                            c = strs[0][num];                            break;                        }                    }                    else                        return ret;                }            }        }    }    };

【LeetCode】Longest Common Prefix