zoj 2744 Palindromes

Palindromes

Time Limit: 2 Seconds      Memory Limit: 65536 KB

A regular palindrome is a string of numbers or letters that is the same forward as backward. For example, the string "ABCDEDCBA" is a palindrome because it is the same when the string is read from left to right as when the string is read from right to left.

Now give you a string S, you should count how many palindromes in any consecutive substring of S.

Input

There are several test cases in the input. Each case contains a non-empty string which has no more than 5000 characters.

Proceed to the end of file.

Output

A single line with the number of palindrome substrings for each case.

Sample Input

aba
aa

Sample Output

4
3

题意:求一个串的所有回文字串的个数,这里要讨论串是奇数串还是偶数串,我的处理办法是将其变成奇数串,详细见代码。

 1 #include <iostream>
 2 #include <string>
 3 #include <cstdio>
 4 using namespace std;
 5 int main(){
 6     string s1, s2 = "#";
 7     int left, right, count;
 8     while(cin >> s1){
 9         s2 = "#";
10         int len1 = s1.length();
11         //将串变成奇数串,避免分情况讨论,以前学习求最长回文字串的一个算法,看到的处理办法,挺好的 
12         for(int i = 0; i < len1; i++){
13             s2 += s1[i];
14             s2 += '#';
15         }
16         int len2 = s2.length();
17         count = len1;//每个字符本身都算一个回文串 
18         for(int i = 1; i < len2 - 1; i++){
19             left = i - 1;
20             right = i + 1;
21             //中心向外扩散,一遇到不是回文串,那么再向外扩散的串都不是回文串 
22             while(left >= 0 && right < len2 && s2[left] == s2[right]){
23                 if(s2[left] != '#')
24                     count++;
25                 left--;
26                 right++;
27             }
28         }
29         printf("%d\n", count);
30     }
31     return 0;
32 }

 

posted @ 2017-03-10 11:24  琴影  阅读(169)  评论(0编辑  收藏  举报