UVA353 LA5247 Pesky Palindromes【回文】

A palindrome is a sequence of one or more characters that reads the same from the left as it does from the right. For example, Z, TOT and MADAM are palindromes, but ADAM is not.
    Your job, should you choose to accept it, is to write a program that reads a sequence of strings and for each string determines the number of UNIQUE palindromes that are substrings.
Input
The input file consists of a number of strings (one per line), of at most 80 characters each, starting in column 1.
Output
For each non-empty input line, the output consists of one line containing the message:
The string ‘input string’ contains nnnn palindromes.
where input string is replaced by the actual input string and nnnn is replaced by the number of UNIQUE palindromes that are substrings.
Note:
See below the explanation of the sample below
• The 3 unique palindromes in ‘boy’ are ‘b’, ‘o’ and ‘y’.
• The 4 unique palindromes in ‘adam’ are ‘a’, ‘d’, ‘m’, and ‘ada’.
• The 5 unique palindromes in ‘madam’ are ‘m’, ‘a’, ‘d’, ‘ada’, and ‘madam’.
• The 3 unique palindromes in ‘tot’ are ‘t’, ‘o’ and ‘tot’.
Sample input
boy
adam
madam
tot
Sample output
The string ‘boy’ contains 3 palindromes.
The string ‘adam’ contains 4 palindromes.
The string ‘madam’ contains 5 palindromes.
The string ‘tot’ contains 3 palindromes.

Regionals 1990 >> North America - Southeast USA

问题链接UVA353 LA5247 Pesky Palindromes
问题简述:(略)
问题分析
    统计一个字符串的回文子串的数量。
    采用暴力法解决,即求出所有子串再进行计算。这个题关键是如何去掉重复的子串再进行统计。程序中,用STL的set来去除重复。用STL实现,时间上要慢许多。想要提高程序运行速度,还是用字符数组。
程序说明:(略)
参考链接:(略)
题记:(略)

AC的C++语言程序如下:

/* UVA353 LA5247 Pesky Palindromes */

#include <bits/stdc++.h>

using namespace std;

bool is_pal(const char *s, int start, int end)
{
    while(start < end)
        if(s[end] != s[start]) return false;
        else start++, end--;
    return true;
}

int main()
{
    string s;
    while(cin >> s) {
        int cnt = 0;
        set<string> ss;
        for(int i = 0; i < (int)s.length(); i++)
            for(int j = 0; j <= i; j++) {
                string t = s.substr(j, i - j + 1);
                if(ss.find(t) == ss.end()) {
                    if(is_pal(s.c_str(), j, i))
                        cnt++;
                    ss.insert(t);
                }
           }

        printf("The string \'%s\' contains %d palindromes.\n", s.c_str(), cnt);
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/tigerisland45/article/details/89505158