【回文子串的个数】HDU1544Palindromes【字符缩距/奇偶判断】
来源:互联网 发布:手机 拔号软件 编辑:程序博客网 时间:2024/05/21 03:29
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1544
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.
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.
Proceed to the end of file.
Output
A single line with the number of palindrome substrings for each case.
Sample Input
abaaa
Sample Output
43
奇偶回文判断AC代码: 时间复杂度O(n^2)
#include<iostream>#include<cstring>#include<string>using namespace std;int main(){ string s; cin.sync_with_stdio(false); while(cin>>s){ int len=s.size(); int ans=len; // 长度为1的个数; for(int i=0;i<len;i++){ int l=i-1,r=i+1; // 以i为中心的奇数长度回文子串的判断; while(l>=0&&r<len&&s[l]==s[r]){ l--,r++; ans++; } l=i,r=i+1; // 以i为中心的偶数长度回文子串的判断; while(l>=0&&r<=len&&s[l]==s[r]){ l--,r++; ans++; } } cout<<ans<<endl; } return 0;}
字符缩距AC代码: 字符串所有字符都不同,最差复杂度O(n^2) 相对于奇偶判断效率还是更高的
#include<iostream>#include<cstring>#include<string>using namespace std;int Hash[5500];int main(){ string s; cin.sync_with_stdio(false); while(cin>>s){ memset(Hash,0,sizeof(Hash)); string str=""; str+=s[0]; int k=0; Hash[0]=1; for(int i=1;i<s.size();i++){ if(s[i]==s[i-1]) Hash[k]++; else{ k++; Hash[k]=1; str+=s[i]; } } k++; int ans=0; for(int i=0;i<k;i++) ans+=(1+Hash[i])*Hash[i]/2; for(int i=0;i<k;i++){ int a=i-1; int b=i+1; if(a<0||b>=k) continue; // 一言不合就跳过 int flag=0; while(str[a]==str[b]&&Hash[a]==Hash[b]){ ans+=Hash[a]; a--; b++; if(a<0||b>=k){ flag=1; break; } } if(flag==0&&str[a]==str[b]){ ans+=min(Hash[a],Hash[b]); } } cout<<ans<<endl; } return 0;}
0 0
- 【回文子串的个数】HDU1544Palindromes【字符缩距/奇偶判断】
- 求奇偶子回文串个数
- 回文子串的个数
- hdu 1544 回文子串的个数
- 判断回文串,判断回文数,最长回文串,回文串的个数
- 判断输入一串数字的奇偶个数
- 字符串的最大回文子串判断
- 【算法】最长回文子串的判断
- 判断字符串是否是回文字符串或者是否含有回文字符子串
- hdu 1544(求回文子串的个数)
- hdu 1544 连续回文子串的个数 构造法
- KMP算法求公共回文子串的个数
- 判断回文字符串(给定开始位置和字符个数)
- 判断字符,字符串的个数
- 最长回文子串、最长回文子序列、回文子序列个数
- 程序员面试题精选(37):判断字符串是否是回文字符串或者是否含有回文字符子串
- 每天一道算法题1 判断字符串是否是回文字符串或者是否含有回文字符子串
- 最长公共子串、最长公共子序列、最长回文子串、最长回文子序列、回文子串个数
- 苹果加急信
- MySQL存储引擎中的MyISAM和InnoDB区别详解
- TabBar高度修改以及UITabBarItem坐标移动
- Android-AS开源好的项目引用-个人心得
- HDU5620 KK's Steel(C++语言版)
- 【回文子串的个数】HDU1544Palindromes【字符缩距/奇偶判断】
- Lucene5.5对索引进行搜索
- 百度地图API
- Linux内核中的PID散列表实例
- Win32 常用数据类型
- sar命令
- 机器学习资源
- Qt 编译时遇到 error: [debug/qrc_music.cpp] Error 1
- 界面设计,事件处理--GUI编程的核心--