@lihuawei:
vivo2024C/C++笔试题9.12给定一个字符串s,找到同时作为前缀和后缀最长字符串的长度。前缀和后缀不应重叠。#include <iostream>#include <vector>using namespace std;int prefixSuffixLength(string s) {    int n = s.length();    vector<int> 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;}
点赞 3
评论 1
全部评论

相关推荐

08-14 11:30
门头沟学院 Java
失去了成为米孝子的机会
投递小米集团等公司10个岗位
点赞 评论 收藏
分享
苍蓝星上艾露:这简历。。。可以试试我写的开源简历优化工具https://github.com/weicanie/prisma-ai
点赞 评论 收藏
分享
我只是一个小白菜:我还用不惯m4,也是山猪吃不了细糠了
投递字节跳动等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务