[LeetCode]Longest Common Prefix

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

这个很简单,看代码便知

// LongestCommonPrefix.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <vector>
#include <string>
#include <iostream>
using namespace std;
class Solution {
public:
	string longestCommonPrefix(vector<string> &strs) {
		int index = 0;
		if (strs.size()==0)
		{
			return "";
		}
		if (strs.size() == 1)
			return strs[0];
		while (true)
		{
			bool eq = true;
			char tempC = strs[0][index];
			for (int i = 1; i < strs.size(); i++)
			{
				if (index >= strs[i].size())
				{
					eq = false;
					break;
				}
				if (strs[i][index] != tempC)
				{
					eq = false;
					break;
				}
				
			}
			if (!eq)
				break;
			index++;
		}
		return strs[0].substr(0,index);
	}
};
int _tmain(int argc, _TCHAR* argv[])
{
	Solution ss;
	vector<string>res;
	//res.push_back("aabbbdkajsk");
	res.push_back("aabuiuiouiou");
	string fres = ss.longestCommonPrefix(res);
	cout << fres << endl;
	system("pause");
	return 0;
}

  

posted @ 2014-10-17 18:52  supernigel  阅读(116)  评论(0编辑  收藏  举报