LeetCode 14: Longest Common Prefix

Posted mfmdaoyou

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 14: 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) {
       	int length = strs.size();
		if (length <= 0)
			return "";
		string prefix = strs[0];
		int i, j;
		for (i=1; i<length; i++)
		{
			string tmpStr = strs[i];
			if (prefix.length()==0 || tmpStr.length()==0)
				return "";
			int len = min(prefix.length(), tmpStr.length());
			for (j=0; j<len; j++)
			{
				if (prefix[j] != tmpStr[j])
					break;
			}
			prefix = prefix.substr(0,j);
		}
		return prefix;
    }
};





以上是关于LeetCode 14: Longest Common Prefix的主要内容,如果未能解决你的问题,请参考以下文章

leetcode14. longest common prefix

Leetcode 14. Longest Common Prefix

Leetcode 14 Longest Common Prefix

Leetcode14. Longest Common Prefix

LeetCode 14: Longest Common Prefix

leetcode 14. Longest Common Prefix