LeetCode 014. Longest Common Prefix

Longest Common Prefix

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.size()==0) return "";
		string result = strs[0];
		int i = 1;
		while(i<strs.size())
		{
			result = comprefix(result, strs[i]);
			i++;
		}
        return result;
    }

	string comprefix(string a, string b)
	{
		string result;
		int i=0, j=0;
		while(i<a.length() && j<b.length() && a[i] == b[j])
		{
			i++;
			j++;		
		}
		result = a.substr(0,i);
		return result;
	}
};


猜你喜欢

转载自blog.csdn.net/wanghuiqi2008/article/details/42835687