力扣14.最长公共前缀

题目: 传送门
题意: 题目给出多个字符串,求出字符串的最长公共前缀,我们要知道字符前缀是什么,我们举个例子:字符串s:“abcdef” ,那么字符串的前缀有:[“a”,“ab”,“abc”,“abcd”,“abcde”,“abcdef”],字符串前缀的意思是从字符串的第一个开始,现在求这些字符串的最长公共前缀我们只需要将两个字符串的最长公共前缀保存成一个字符串,然后和其他字符串一次求最长公共前缀,如何求最长公共前缀呢?我只需要一个while循环就可以了:

string Solution::longFind(string s1, string s2) {
    
    
	string s;
	int len1 = s1.size();
	int len2 = s2.size();
	int i = 0, j = 0;
	while (i < len1 && j < len2) {
    
    
		if (s1[i] == s2[j]) {
    
    
			s.push_back(s1[i]);
			i++;
			j++;
		}
		else {
    
    
			return s;
		}
	}
	return s;
}

这个函数的功能就是获取最长公共前缀。
我们看完整代码:

在这里插入图片描述

#include<iostream>
#include<vector>
using namespace std;
class Solution {
    
    
public:
	string longestCommonPrefix(vector<string>& strs);
	string longFind(string s1, string s2);
};

string Solution::longestCommonPrefix(vector<string>& strs) {
    
    
	string s;
	s = strs[0];
	for (int i = 1; i < strs.size(); i++) {
    
    
		s = longFind(s, strs[i]);
	}
	return s;
}

string Solution::longFind(string s1, string s2) {
    
    
	string s;
	int len1 = s1.size();
	int len2 = s2.size();
	int i = 0, j = 0;
	while (i < len1 && j < len2) {
    
    
		if (s1[i] == s2[j]) {
    
    
			s.push_back(s1[i]);
			i++;
			j++;
		}
		else {
    
    
			return s;
		}
	}
	return s;
}
int main() {
    
    
	string str;
	vector<string>strs;
	while (1) {
    
    
		cin >> str;
		strs.push_back(str);
		if (cin.get() == '\n')
			break;
	}
	Solution ans;
	cout << ans.longestCommonPrefix(strs) << endl;
	return 0;
}

写完这个题后发现官方题解不止一种方法,官方给了四个题解,四种思路,感兴趣可以看看不同思路。
ヾ(◍°∇°◍)ノ゙
在这里插入图片描述
补充:
在看别人分享的思路的时候,我还看到了一种思路,可以先对字符数组排序,排序之后我们只比较两端的就可以了,果然大佬千千万,而我是菜鸡。
我们看代码:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
    
    
public:
	string longestCommonPrefix(vector<string>& strs);
	string longFind(string s1, string s2);
};

string Solution::longestCommonPrefix(vector<string>& strs) {
    
    
	string s;
	if (strs.empty())
		return string();
	sort(strs.begin(), strs.end());///使用sort函数排序
	s =longFind( strs.front(), strs.back());///font获取vector的头,back获取vector的尾
	return s;
}

string Solution::longFind(string s1, string s2) {
    
    
	string s;
	int len1 = s1.size();
	int len2 = s2.size();
	int i = 0, j = 0;
	while (i < len1 && j < len2) {
    
    
		if (s1[i] == s2[j]) {
    
    
			s.push_back(s1[i]);
			i++;
			j++;
		}
		else {
    
    
			return s;
		}
	}
	return s;
}
int main() {
    
    
	string str;
	vector<string>strs;
	while (1) {
    
    
		cin >> str;
		strs.push_back(str);
		if (cin.get() == '\n')
			break;
	}
	Solution ans;
	cout << ans.longestCommonPrefix(strs) << endl;
	return 0;
}

おすすめ

転載: blog.csdn.net/qq_43840681/article/details/118053726