PAT 1040. Longest Symmetric String
#include<iostream> #include<cstdio> #include<string> #include<cstring> #include<queue> #include<vector> #include<cmath> #include<iomanip> #include<algorithm> using namespace std; //回文有两种情况:aba或者abba,即有对称点和无对称点。 int getSymLen(char *str,int pos) { int len = strlen(str); int iCount1 = 0,low,high; //处理aba的情况 low = pos - 1; high = pos + 1; while(low>=0 && high<len && str[low] == str[high]) { iCount1++; low--; high++; } int len1 = 2*iCount1+1; //处理abba的情况; int iCount2 = 0; low = pos; high = pos + 1; while(low>=0 && high<len && str[low] == str[high]) { iCount2++; low--; high++; } int len2 = 2*iCount2; return len1>len2?len1:len2; } int main() { char str[1005]; gets(str); int maxLen = 1,t,i; int len = strlen(str); for(i=0; i<len; i++) { t = getSymLen(str,i); if(t > maxLen) maxLen = t; } cout<<maxLen<<endl; return 0; }
多学习,多总结。