输入一串数字分别找出其中奇数和偶数的个数

#输入一串数字分别找出其中奇数和偶数的个数

#include <iostream>
using namespace std;

int main()
{
   
   
    int x,a[20];
    int j=0,o=
要解决“输入一个字符串,输出对应的回文子字符串量”这个问题,我们需要明确: **题目是要求找出该字符串中所有可能的回文子串的个数。** 例如: - 输入 `"aba"`,它的回文子串有:`"a"`, `"b"`, `"a"`, `"aba"` → 共 4 个。 - 注意:重复内容但不同位置的也算(如两个 `"a"`)。 --- ### ✅ 解法:中心扩展法(Expand Around Centers) 我们可以枚举每一个可能的回文中心(包括单字符中心双字符中心),然后向两边扩展判断是否为回文。 #### 时间复杂度:O(n²) #### 空间复杂度:O(1) --- ### Python 实现代码: ```python def count_palindromic_substrings(s: str) -> int: if not s: return 0 count = 0 n = len(s) for i in range(n): # 奇数长度回文,以 i 为中心 left = right = i while left >= 0 and right < n and s[left] == s[right]: count += 1 left -= 1 right += 1 # 偶数长度回文,以 i i+1 为中心 left = i right = i + 1 while left >= 0 and right < n and s[left] == s[right]: count += 1 left -= 1 right += 1 return count ``` --- ### 示例使用: ```python print(count_palindromic_substrings("aba")) # 输出: 4 print(count_palindromic_substrings("aaa")) # 输出: 6 print(count_palindromic_substrings("abc")) # 输出: 3 ``` --- ### 代码解释: - 外层循环 `for i in range(n)` 遍历每个可能的回文中心。 - 第一个 `while` 循环处理奇数长度回文(如 "aba"),中心是单个字符。 - 第二个 `while` 循环处理偶数长度回文(如 "abba"),中心在两个字符之间。 - 每次满足 `s[left] == s[right]` 就说明找到一个新的回文子串,`count += 1`。 - 扩展直到不匹配或越界为止。 --- ### 进阶优化(可选): 可以使用 **Manacher 算法** 在 O(n) 时间内完成,但实现较复杂,适用于大规模据。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值