【Leetcode 14】Longest Common Prefix

本文介绍了一种简单而有效的方法来查找一组字符串中的最长公共前缀。通过遍历字符串数组并比较每个字符,该算法能够确定所有输入字符串共享的最长开头部分。示例代码使用C++实现,并提供了具体的应用实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

If there is no common prefix, return an empty string "".

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

 

题目翻译:

一个vector<string> vec里边存了很多string,求这些string的最大相同的头部分。

很简单的题目,从头依次遍历即可,如果vec是空的,返回空,如果vec是1,则直接把结果返回,如果vec>=2,继续查找公共最大的范围。

#include<iostream>
#include<cmath>
#include<string>
#include<vector>


using namespace std;


class Solution{
public:
	string longestCommonPrefix(vector<string> &vec)
	{
		string str="";
		int n=vec.size();
		if(n==0)
			return str;
		if(n==1)
		{
			str=vec[0];
			return str;
		}

		int count=0;
		int istrue=0;


		int max=vec[0].length();
		while(count<max)
		{		
			char temp=vec[0][count];
			for(int i=1;i<n;i++)
			{
				if(temp!=vec[i][count])
					istrue=1;

			}
			if(istrue==1)
				break;
			else
				count++;
		}
		for(int i=0;i<count;i++)
			str+=vec[0][i];

		return str;
	
	}
};



int main()
{   
	vector<string> vec;
	vec.push_back("flower");
	vec.push_back("flow");
	vec.push_back("flight");

	Solution so;
	string str=so.longestCommonPrefix(vec);
	cout<<str<<endl;




	system("pause");
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值