标签:思路 std lin www. pre IV example case ica
Given a string, you are supposed to output the length of the longest symmetric sub-string. For example, given "Is PAT&TAP symmetric?", the longest symmetric sub-string is "s PAT&TAP s", hence you must output 11.
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:
11
题目大意:找出字符串最大对称子串的长度;
思路:通过中心扩展来找对称子串, 从一个字符串的中心向两边扩展,就记录左右两边相等的字符个数;
len1=SymString(s, i, i); 查找以单个字符为中心的对称子串
len2=SymString(s, i, i+1) 查找以两个字符为中心的对称子串
注意点: max的初始值应该为1, 而不是0;
输入应该用getline(), 否则会应为空格的出现, 导致输入不完整
类似的题:https://www.cnblogs.com/mr-stn/p/9196718.html
1 #include<iostream> 2 #include<vector> 3 #include<string> 4 using namespace std; 5 int SymString(string &s, int l, int r){ 6 int left=l, right=r, n=s.size(); 7 while(left>=0 && right<n && s[left]==s[right]){ 8 left--; 9 right++; 10 } 11 return right-left-1; 12 } 13 int main(){ 14 string s; 15 getline(cin, s); 16 int max=1; 17 for(int i=0; i<s.size()-1; i++){ 18 int len1=SymString(s, i, i); 19 int len2=SymString(s, i, i+1); 20 int len=len1>len2 ? len1 : len2; 21 if(len>max) max=len; 22 } 23 cout<<max; 24 return 0; 25 }
PAT 1040 Longest Symmetric String (25)
标签:思路 std lin www. pre IV example case ica
原文地址:https://www.cnblogs.com/mr-stn/p/9216982.html