14. Longest Common Prefix

14. Longest Common Prefix

题目

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

解析

  • leetcode官网给出了水平,垂直,二分,trie树的方法;但是感觉都需要把所有字符串遍历一遍,考虑用简单的水平遍历
class Solution_14 {
public:
	string longestCommonPrefix(vector<string> &strs) {
		if (strs.size() == 0)
		{
			return ""; //返回NULL 错误
		}
		if (strs.size() == 1)
		{
			string str = strs[0];
			return str;
		}
		string ret = strs[0];
		int max_comlen = ret.size();
		int j = 0;
		for (int i = 1; i < strs.size(); i++)
		{
			j = 0;
			while (strs[i][j] == ret[j] && j < ret.size()) //优化:记录上一次匹配最远的位置,下一次不超过这个距离
			{
				j++;
			}
			max_comlen = min(max_comlen, j); //取的是最小长度的公共子串;min=('a','a','b')=0;
		}
		return ret.substr(0, max_comlen);
	}
};

题目来源

原文地址:https://www.cnblogs.com/ranjiewen/p/8313049.html