题解 | #密码截取#

密码截取

https://www.nowcoder.com/practice/3cd4621963e8454594f00199f4536bb1

#include <iostream>
#include <vector>
using namespace std;

/*求回文子串,动态规划方程:
用双指针i j分别表示子串起点终点的索引值
dp[i][j]=true(i==j,1个字符一定是回文)
dp[i][j]=(s[i]==s[j])?(i=j-1,则只判断s[i]=s[j]与否)
dp[i][j]=(s[i]==s[j] && dp[i+1][j-1])(j>i+1,则需要判断子串是否回文,以及子串加上两端新字符是否回文)*/
int findLongestPasswd(string str){
    int max_Length=1;
    vector<vector<int>> dp(str.length(),vector<int>(str.length(),0));
    for(int i=0;i<str.length();i++){
        dp[i][i]=1;
    }

    for(int L=2;L<=str.length();L++){   //遍历每一个长度≥2的子串
        for(int j=0;j<str.length();j++){    //子串的起点
            if(L+j>str.length()){   //如果超界,直接退出循环层2
                break;
            }

            if(L==2){
                dp[j][j+L-1]=(str[j]==str[j+L-1])?1:0;
            }
            else{
                dp[j][j+L-1]=(str[j]==str[j+L-1])?dp[j+1][j+L-2]:0;
            }

            if((dp[j][j+L-1]==1)&&(L>max_Length)){
                max_Length=L;
            }
        }
    }
    return max_Length;
}

int main() {
    string str;
    cin>>str;
    int res=findLongestPasswd(str);
    printf("%d",res);
    return 0;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

想问各位佬,这是挂了吗
糖糖p:同学,瞅瞅我司,医疗独角兽,校招刚开,名额有限,先到先得,我的主页最新动态,绿灯直达,免笔试~
投递小米集团等公司10个岗位
点赞 评论 收藏
分享
牛客59349152...:没有让你做出个前后端页面,然后又不要你就知足了吧😂
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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