识别回文序列并根据给定数字对它们进行计数

recognize palindromic sequences and count them on a given number

我有一个像这样的整数输入 1213121

我想数一下有多少个回文序列(输出必须是5个回文序列)

因为第一个回文序列是121.

第二个是1213121。

第三个是21312。

第四个是131

第五个是121

我试图在 google 上搜索,但我发现的所有内容都是拆分数字或识别回文数字。

你能帮忙吗?

感谢您的宝贵时间+

您没有指定您的 DBMS,所以这里有一个 TSQL 解决方案,它至少向您展示了一个简单的方法来完成您需要做的事情。

DECLARE @input VARCHAR(25) = '1213121';

WITH CTE_nums --just a list of numbers from 1 to the length of the input which is 7 in this case
AS
(
    SELECT 1 AS pos
    UNION ALL
    SELECT pos + 1
    FROM CTE_nums
    WHERE pos < LEN(@input)
)

SELECT  SUBSTRING(@input,A.pos,B.pos - A.pos + 1) AS palindrome_seq
FROM CTE_nums A
CROSS JOIN CTE_nums B --cross join to find every possible combination of those numbers
WHERE A.pos <= B.pos - 2 --only choose strings that are at least 2 characters long(not sure if you want it to be 2 or 3)
AND SUBSTRING(@input,A.pos,B.pos - A.pos + 1) = REVERSE(SUBSTRING(@input,A.pos,B.pos - A.pos + 1)) --check if that substring is the same reversed substring

结果:

palindrome_seq
-------------------------
121
1213121
21312
131
121