PAT甲级——A1040 Longest Symmetric String
发布时间:2020-12-13 23:37:45 所属栏目:Linux 来源:网络整理
导读:Given a string,you are supposed to output the length of the longest symmetric sub-string. For example,given? Is PATTAP symmetric? ,the longest symmetric sub-string is? s PATTAP s ,hence you must output? 11 . Input Specification: Each input
Given a string,you are supposed to output the length of the longest symmetric sub-string. For example,given? Input Specification:Each input file contains one test case which gives a non-empty string of length no more than 1000. Output Specification:For each test case,simply print the maximum length in a line. Sample Input:Is PAT&TAP symmetric? Sample Output:
1 #include <iostream> 2 #include <string> 3 #include <algorithm> 4 5 using namespace std; 6 string str,t1,t2; 7 int res = 1; 8 //最普通的遍历 9 void way1() 10 { 11 for (int i = 0; i < str.length(); ++i) 12 { 13 for (int j = str.length() - 1; j > i; --j) 14 { 15 t1.assign(str.begin() + i,str.begin() + j + 1); 16 t2.assign(t1.rbegin(),t1.rend()); 17 if (t1 == t2) 18 res = res > t1.length() ? res : t1.length(); 19 } 20 } 21 } 22 23 //利用回文子串中心的两边相同 24 void way2() 25 { 26 for (int i = 0; i < str.size(); ++i) { 27 int j; 28 for (j = 1; i - j >= 0 && i + j < str.size() && str[i + j] == str[i - j]; ++j);//以当前字符为回文中心查找最长回文子串 29 res= max(res,2 * j - 1);//更新回文子串最大长度 30 for (j = 0; i - j >= 0 && i + j + 1 < str.size() && str[i - j] == str[i + 1 + j]; ++j);//以当前字符为回文中心左侧字符查找最长回文子串 31 res = max(res,2 * j);//更新回文子串最大长度 32 } 33 } 34 35 //使用动态规划 36 void way3() 37 { 38 int dp[1010][1010]; 39 for (int i = 0; i < str.length(); i++) 40 { 41 dp[i][i] = 1; 42 if (i < str.length() - 1 && str[i] == str[i + 1]) 43 { 44 dp[i][i + 1] = 1; 45 res = 2; 46 } 47 } 48 for (int L = 3; L <= str.length(); L++) { 49 for (int i = 0; i + L - 1 < str.length(); i++) { 50 int j = i + L - 1; 51 if (str[i] == str[j] && dp[i + 1][j - 1] == 1) { 52 dp[i][j] = 1; 53 res = L; 54 } 55 } 56 } 57 } 58 59 int main() 60 { 61 getline(cin,str); 62 way1(); 63 cout << res << endl; 64 return 0; 65 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |