【LeetCode】14. Longest Common Prefix

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

题目就没看懂,在讨论区看到了对这个题的解释,如下:

It seems that it is not to check between pair of strings but on all the strings in the array.

For example:

  1. {“a”,“a”,“b”} should give “” as there is nothing common in all the 3 strings.

  2. {“a”, “a”} should give “a” as a is longest common prefix in all the strings.

  3. {“abca”, “abc”} as abc

  4. {“ac”, “ac”, “a”, “a”} as a.

自己的思路如下:

1.公共变量comfrefix,分别与其他字符串比较

2.比较两个字符串中的每个字符是否相同,更新comfrefix,若该次比较没有共同的字符则返回空

3.重复1和2,结束后返回comfrefix

自己的代码写的很啰嗦,主要是下面几点没有考虑到:

1.如果有公共子字符串,那么每一个字符串都包含该子字符串

2.循环的选择,选第一个字符串中每个字符与其他字符串中的字符比较

3.建一个空字符串,有公共字符则加到该字符串上

讨论区的思路:

  1. Pick a character at i=0th location and compare it with the character at that location in every string.

  2. If anyone doesn’t have that just return “”

  3. Else append that character in to the result.

  4. Increment i and do steps 1-3 till the length of that string.

  5. return result.

代码如下:

class Solution
{
public:
	string longestCommonPrefix(vector<string>& strs)
	{
		string prefix = "";
		if (strs.size() == 0) return "";

		for (int k = 0; k < strs[0].size(); k++)//第一个字符串中的每个字符拿住来与其他字符串中的字符做比较
		{
			int i = 1;
			for (; i<strs.size() && strs[i].size()>k; i++)//依次拿出他字符串
			{
				if (strs[i][k] != strs[0][k])
					return prefix;
			}
			if (i == strs.size())
				prefix += strs[0][k];
		}
		return prefix;
	}
};
这段代码写的很精简,lz需要好好学习一下
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值