C++ LeetCode简单程序:最长公共前缀

写在最前
猛一看简单,再一看有点难,然后做着做着简单了。

题目描述
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。

示例 1:
输入: [“flower”,“flow”,“flight”]
输出: “fl”

示例 2:
输入: [“dog”,“racecar”,“car”]
输出: “”
解释: 输入不存在公共前缀。

说明:
所有输入只包含小写字母 a-z 。

实现方法

#include
#include
#include
using namespace std;

class Solution {
public:
	string longestCommonPrefix(vector& strs) {
		string common="";
		int count = 0;
		for (int i = 0; i < strs.size(); i++)			//遍历字符串的每个字母
		{
			for (int j = 0; j < strs.size() - 1; j++)		//遍历每个字符串
			{
				if (strs[j][i] == strs[j+1][i])			//判断每个字符串的对应字母是否一样
				{
					count++;							//如果一样,计数
				}
			}
			if (count == strs.size() - 1)				//计数与字符串-1一致,则为共有字母
				common.push_back(strs[i][i]);
			count = 0;									//重新计数
		}
		return common;
	}
};

int main()
{
	Solution s;
	string temp;
	vector str;
	cout << "请输入a~z之间的英文字母组成的单词:";
	while (cin>>temp && temp!="exit")	//exit退出输入
	{
		str.push_back(temp);
		
	}
	string rtn = s.longestCommonPrefix(str);
	cout << rtn << endl;

	system("pause");
	return 0;
}

你可能感兴趣的:(C++LeetCode)