码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Longest Common Prefix

时间:2014-05-15 13:27:07      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   c   color   

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


class Solution {
public:
    string longestCommonPrefix(vector<string> &strs) 
    {
	std::string ans("");
	//字符串数组为空
	if(strs.size()==0)
	{
		return ans;
	}
	//字符串数组大小为1
	if(strs.size() == 1)
	{
		return strs[0];
	}
	//字符串数组大小大于1
	int count = 0;
	//j用来表示列,i用来表示第几个字符串
	for (int j = 0; j < INT_MAX; j++)
	{
		std::vector<char> result;
		for (int i = 0; i < strs.size(); i++)
		{
			if(j < strs[i].size() && strs[i].size() != 0)
			{
				//各个字符串的j列都和第0个字符串的j列比较
				if (strs[i][j]==strs[0][j]&&strs[i][j] != ‘\0‘)
				{
					result.push_back(strs[i][j]);	
				}  
				else
				{
					break;
				}
			}
		}
		//若j列都相同,则count++;有一个不同,则停止比较
		if (result.size() == strs.size())
		{
			count++;
		}
		else
		{
			j = INT_MAX - 1;
			break;
		}
	}

	if (count >= 0)
	{
		for (int i = 0; i < count; i++)
		{
			ans = ans + strs[0][i];			
		}	
	}
	return ans;
    }
};


[LeetCode]Longest Common Prefix,布布扣,bubuko.com

[LeetCode]Longest Common Prefix

标签:style   blog   class   code   c   color   

原文地址:http://blog.csdn.net/jet_yingjia/article/details/25873799

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!