最长回文字符串,最长回文字符串长度。之前转载过一篇马拉车算法,从来没实现过,刚好今天遇到了类似的题,实现一下。
原理及操作:
1,在源字符串每一个字符的前后都加上一个不会出现的字符,例如 '#'。
2,遍历新字符串的字符,确定每个字符可以组成的最长回文串。写入回文数组中。
3,找到回文数组中最大的数字,就是最长回文串的长度,所组成的回文串就是最长回文串。
当然,如果不想找到所有的回文串,完全不需要回文数组,只需要两个变量保存最长回文串长度以及最长回文串的其实位置,在最后return语句中直接复刻该最长回文串。
string longestPalindrome(string s) {
if (s.empty()) {
return "";
}
string s_tmp;
for(int i = 0; i < s.length(); ++i) {
s_tmp = s_tmp + ' ' + s[i];
}
s_tmp += ' ';
int iSize = 0, iPos = 0;
for(int i = 1; i < s_tmp.length(); ++i) {
int iTmpSize = 0;
int iLeft = i-1;
int iRight = i+1;
while(iLeft >= 0 && iRight < s_tmp.length() && s_tmp[iLeft] == s_tmp[iRight]) {
--iLeft;
++iRight;
++iTmpSize;
}
if(iSize < iTmpSize) {
iSize = iTmpSize;
iPos = iLeft < 0 ? 0 : iLeft;
//scout<<iPos<<" "<<iSize<<endl;
}
}
//cout<<s.substr(1,3)<<endl;
//cout<<(iPos+1)/2<<" "<<(iPos+1)/2+iSize-1<<endl;
return s.substr((iPos+1)/2, iSize);
}
int main()
{
cout<<longestPalindrome("b")<<endl;
cout<<longestPalindrome("bb")<<endl;
cout<<longestPalindrome("cbb")<<endl;
cout<<longestPalindrome("cbbd")<<endl;
cout<<longestPalindrome("bcbcb")<<endl;
cout<<longestPalindrome("abacdc")<<endl;
}
写代码的时候,还有个小插曲,函数longestPalindrome中,string调用了substr函数。刚开始我以为substr接受两个参数的参数含义分别为 "起始位置,结束为止"。于是,我传递的参数分别为 (iPos+1)/2和(iPos+1)/2+iSize。结果总是不对。排除掉逻辑问题之后,我终于把怀疑的目光挪到了substr上。
果真,两个参数的substr() 方法中,参数含义分别为 "起始为止,切割个数"。