PAT.A1040 Longest Symmetric String

Back to ContentsInsert picture description here

Title

Find the length of the longest palindrome substring of a string.

Sample (can be copied)

10
-10 1 2 3 4 -5 -23 3 7 -21
//output
10 1 4

important point

  1. This problem can be solved using the brute force method and dynamic programming method.
#include<bits/stdc++.h>
using namespace std;

int dp[1010][1010],ans=1;
int main(){
	string s;
	getline(cin,s);
	for(int i=0;i<s.size();i++){//边界
		dp[i][i]=1;
		if(i<s.size()-1&&s[i]==s[i+1]){
			dp[i][i+1]=1;
			ans=2;
		}
	}
	for(int l=3;l<=s.size();l++){
		for(int i=0;i+l-1<s.size();i++){//枚举起始点
			int j=i+l-1;//子串的右端点
			if(s[i]==s[j]&&dp[i+1][j-1]==1){
				dp[i][j]=1;
				ans=l;
			}
		}
	}
	cout<<ans;
    return 0;
}
Published 177 original articles · won praise 5 · Views 6646

Guess you like

Origin blog.csdn.net/a1920993165/article/details/105594171