C++:求解给定字符串的前缀

本文介绍了一个使用C++实现的程序,该程序能够接收不定数量的字符串对作为输入,并找出每对字符串之间的最长公共前缀。通过逐字符比较的方法来确定共同前缀,并输出结果。

C++:求解给定字符串的前缀(2017.3.29)


输入格式:

输入数目不定的多对字符串,每行两个,以空格分开。 例如:

filename filepath

Tom Jack

输出格式:

返回两个字符串的最大前缀,例如:

The common prefix is file

No common prefix

输入样例:

filename filepath
Tom Jack

输出样例:

The common prefix is file
No common prefix


#include<cstring>
#include<iostream>
#include<string>
using namespace std;
int main()
{
	string s1,s2;
	char s[10000];
	int i;
	while(cin >> s1 >> s2)
	{
		int flag = 0;
		int len = s1.size();
		if(s2.size() < len)
			len = s2.size() ;
		for(i = 0;i< len;++i)
		{
			if(s1[i] == s2[i])
			{
				s[i] = s1[i];
				flag = 1;
			}
			else 
				break;
		}
		if(flag)
		    cout << "The common prefix is " << s << endl;
		else 
		    cout << "No common prefix" << endl;
	}
	return 0;
}
### C++ 字符串相关的笔试题解析 #### 题目一:字符串反转 编写一个函数 `reverseString`,用于将给定字符串原地反转。 ```cpp void reverseString(std::string& s) { int n = s.size(); for (int i = 0; i < n / 2; ++i) { std::swap(s[i], s[n - i - 1]); } } ``` 此代码通过交换首尾字符的方式实现了字符串的反转功能[^1]。 --- #### 题目二:删除重复字符 设计一个算法,在不使用额外空间的情况下,移除字符串中的重复字符并保持原有顺序。 ```cpp std::string removeDuplicates(std::string str) { bool seen[256] = {false}; std::string result; for (char c : str) { if (!seen[c]) { seen[c] = true; result += c; } } return result; } ``` 上述代码利用布尔数组记录已访问过的字符,并构建一个新的无重复字符的结果字符串。 --- #### 题目三:判断回文串 实现一个函数,用来检测输入的字符串是否为回文串(忽略大小写和非字母字符)。 ```cpp bool isPalindrome(const std::string& s) { int left = 0, right = s.length() - 1; while (left < right) { while (left < right && !isalnum(s[left])) ++left; while (left < right && !isalnum(s[right])) --right; if (tolower(s[left]) != tolower(s[right])) return false; ++left; --right; } return true; } ``` 该解决方案通过双指针法跳过无关字符,比较两端字符是否相等来验证回文性质[^3]。 --- #### 题目四:子序列匹配 给定两个字符串 `s` 和 `t`,判断 `s` 是否为 `t` 的子序列。 ```cpp bool isSubsequence(const std::string& s, const std::string& t) { int indexS = 0, indexT = 0; while (indexS < s.size() && indexT < t.size()) { if (s[indexS] == t[indexT]) ++indexS; ++indexT; } return indexS == s.size(); } ``` 这段代码逐步遍历目标字符串 `t` 并尝试找到源字符串 `s` 中的所有字符,最终确认其是否构成有效子序列[^2]。 --- #### 题目五:最长公共前缀 求解多个字符串之间的最长公共前缀长度。 ```cpp std::string longestCommonPrefix(const std::vector<std::string>& strs) { if (strs.empty()) return ""; std::string prefix = strs[0]; for (const auto& str : strs) { size_t matchLength = 0; while (matchLength < prefix.size() && matchLength < str.size() && prefix[matchLength] == str[matchLength]) ++matchLength; prefix.resize(matchLength); if (prefix.empty()) break; } return prefix; } ``` 这里采用逐字对比的方法不断缩短候选前缀直至满足所有字符串的要求。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值