hduoj1544(判斷連續迴文)

Palindromes

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 1509 Accepted Submission(s): 712

Problem Description
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
題解:從某一個開始,然後分偶數和奇數向左向右擴展,遇到不相等就退出,用二維dp會超時。

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char str[5005];
bool dp[5005][5005];
int main(){
    int len,i,j,cnt,l,r;
    while(scanf("%s",str)!=EOF){

        len=strlen(str);
            cnt=len;
        for(i = 0 ; i < len ; i++){
            l=i-1;
            r=i+1;
            while(l>=0&&r<len&&str[l]==str[r]){
                l--;r++;
                cnt++;
            }
            l=i;r=i+1;
            while(l>=0&&r<len&&str[l]==str[r]){
                l--;r++;
                cnt++;
            }           
        }
        printf("%d\n",cnt);
        //cout<<cnt<<endl;
    }
    return 0;
} 
發佈了70 篇原創文章 · 獲贊 5 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章