【发布时间】:2023-04-03 19:10:01
【问题描述】:
我代表朋友发布此内容,因为我认为这很有趣:
取字符串“abb”。通过省略 任何数量的字母小于 我们以 7 结尾的字符串的长度 字符串。
a b b ab ab bb abb
这 4 个是回文。
字符串也一样
“hihellolookhavealookatthispalindromexxqwertyuiopasdfghjklzxcvbnmmnbvcxzlkjhgfdsapoiuytrewqxxsoundsfamiliardoesit”
(长度为 112 的字符串)2^112 - 1 可以组成字符串。
其中有多少是 回文??
下面是他的实现(在 C++ 中,C 也很好)。很长的话很慢;他想知道最快的算法是什么(我也很好奇:D)。
#include <iostream>
#include <cstring>
using namespace std;
void find_palindrome(const char* str, const char* max, long& count)
{
for(const char* begin = str; begin < max; begin++) {
count++;
const char* end = strchr(begin + 1, *begin);
while(end != NULL) {
count++;
find_palindrome(begin + 1, end, count);
end = strchr(end + 1, *begin);
}
}
}
int main(int argc, char *argv[])
{
const char* s = "hihellolookhavealookatthis";
long count = 0;
find_palindrome(s, strlen(s) + s, count);
cout << count << endl;
}
【问题讨论】:
-
每月举办一次编码竞赛的瑞典老杂志(想想 amiga vs c64)曾经有过这个任务。
-
为什么是这个 C、C++ 问题??
标签: c++ algorithm performance