前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >最长公共前缀

最长公共前缀

作者头像
用户3519280
发布2023-07-08 10:52:35
1030
发布2023-07-08 10:52:35
举报
文章被收录于专栏:c++ 学习分享

难度简单2245

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""

示例 1:

代码语言:javascript
复制
输入:strs = ["flower","flow","flight"]
输出:"fl"

示例 2:

代码语言:javascript
复制
输入:strs = ["dog","racecar","car"]
输出:""
解释:输入不存在公共前缀。

提示:

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] 仅由小写英文字母组成
代码语言:javascript
复制
#include <stdio.h>
#include <iostream>
using namespace std;
#include <vector>
 string longestCommonPrefix(vector<string>& strs);
string longestCommonPrefix(vector<string>& strs) {
		string ans;
		if(strs.empty() )return ans;
		int idx=0;
		while(1){
			if(strs[0].empty())return ans;
			char check=strs[0][idx];
			int find=1;
			for(int i=0;i<strs.size();i++){
				if(idx>=strs[i].size()){
					find=0;
					break;
				}
				if(strs[i][idx]!=check){
					find=0;
					break;
				}

			}
							idx++;
				if(find==1)ans+=check;
				else break;
		}
		return  ans;
		//return  strs[1];
    }
int main(void) {
	string str[100]={"flower","flow","flight"};
	//vector<string> strs{"flower","flow","flight"};
	vector<string> strs(str,str+3);
	string s=longestCommonPrefix(strs);
	cout<<"输出是"<<s<<endl;
    return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-05-18,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档