vivo2024C/C++笔试题9.12
给定一个字符串s,找到同时作为前缀和后缀最长字符串的长度。前缀和后缀不应重叠。
#include
#include
using namespace std;
int prefixSuffixLength(string s) {
int n = s.length();
vector nextArr(n, 0);
int length = 0;
int i = 1;
while (i < n) {
if (s[i] == s[length]) {
length++;
nextArr[i] = length;
i++;
}
else {
if (length != 0) {
length = nextArr[length - 1];
}
else {
nextArr[i] = 0;
i++;
}
}
}
// 判断最长前缀后缀是否重叠
int maxLength = nextArr[n - 1];
while (maxLength > n / 2) {
maxLength = nextArr[maxLength - 1];
}
return maxLength;
}
int main() {
string s = "aaaa";
// string s = "aabcdaabc";
// string s = "abcabd";
int length = prefixSuffixLength(s);
cout << "最长前缀后缀的长度为: " << length << endl;
return 0;
}
给定一个字符串s,找到同时作为前缀和后缀最长字符串的长度。前缀和后缀不应重叠。
#include
#include
using namespace std;
int prefixSuffixLength(string s) {
int n = s.length();
vector
int length = 0;
int i = 1;
while (i < n) {
if (s[i] == s[length]) {
length++;
nextArr[i] = length;
i++;
}
else {
if (length != 0) {
length = nextArr[length - 1];
}
else {
nextArr[i] = 0;
i++;
}
}
}
// 判断最长前缀后缀是否重叠
int maxLength = nextArr[n - 1];
while (maxLength > n / 2) {
maxLength = nextArr[maxLength - 1];
}
return maxLength;
}
int main() {
string s = "aaaa";
// string s = "aabcdaabc";
// string s = "abcabd";
int length = prefixSuffixLength(s);
cout << "最长前缀后缀的长度为: " << length << endl;
return 0;
}
全部评论
想问下没收到笔试是不是测评寄了😅
相关推荐
点赞 评论 收藏
分享
汉献帝刘协:公积金随便提的吧,我这里一年可以全提出来一次,不用离职,不用交什么证明,北京不至于那么恶心你
点赞 评论 收藏
分享