UVA353 LA5247 Pesky Palindromes【回文】

本文介绍了一种算法,用于统计给定字符串中独特的回文子串数量。通过使用STL set去除重复,并以暴力法求解所有可能的子串,最终确定其是否为回文。示例输入和输出展示了如何应用此算法。

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值