当前位置:网站首页>409. 最长回文串
409. 最长回文串
2022-07-01 03:23:00 【Sun_Sky_Sea】
409. 最长回文串
原始题目链接:https://leetcode.cn/problems/longest-palindrome/
给定一个包含大写字母和小写字母的字符串 s ,返回 通过这些字母构造成的 最长的回文串 。
在构造过程中,请注意 区分大小写 。比如 “Aa” 不能当做一个回文字符串。
示例 1:
输入:s = “abccccdd”
输出:7
解释:
我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。
示例 2:
输入:s = “a”
输入:1
示例 3:
输入:s = “bb”
输入: 2
提示:
1 <= s.length <= 2000
s 只能由小写和/或大写英文字母组成
解题思路:
统计字符个数,偶数个字符可以分别放在两边,奇数个字符只能只用一种且一次,其中的偶数的字符放在两边,剩下的一个字符,放在中间当分界线。
代码实现:
class Solution:
def longestPalindrome(self, s: str) -> int:
# 统计字符串s的每个字符的个数
import collections
count = collections.Counter(s)
ans = 0
for value in count.values():
# 每次取偶数个字符分别放在回文串的两边
# ans记录的使用字符的个数,即回文串的长度
ans += value // 2 * 2
# 如果value是奇数的话,那么使用一次这样的奇数串
# 因为value中的偶数个字符可以放在回文串的两边
# 剩下的可以放在回文串的中间当做分界线
# 这样的个数是奇数的字符只能使用一种,否则就构不成回文串
if ans % 2 == 0 and value % 2 == 1:
ans += 1
return ans
边栏推荐
- 岭回归和lasso回归
- How to achieve 0 error (s) and 0 warning (s) in keil5
- TEC: Knowledge Graph Embedding with Triple Context
- Pyramid Scene Parsing Network【PSPNet】论文阅读
- Promise中finally的用法
- Bilinear upsampling and f.upsample in pytorch_ bilinear
- Addition without addition, subtraction, multiplication and division
- Split(), split(), slice(), can't you tell?
- ES6解构语法详解
- File upload and download
猜你喜欢

Filter

排序链表(归并排序)

IPv4和IPv6、局域网和广域网、网关、公网IP和私有IP、IP地址、子网掩码、网段、网络号、主机号、网络地址、主机地址以及ip段/数字-如192.168.0.1/24是什么意思?

File upload and download

IPv4 and IPv6, LAN and WAN, gateway, public IP and private IP, IP address, subnet mask, network segment, network number, host number, network address, host address, and IP segment / number - what does

SEM of C language_ Tvariable type

数据交换 JSON

后台系统右边内容如何出现滚动条和解决双滚动条的问题

报错:Plug-ins declaring extensions or extension points must set the singleton directive to true

pytorch nn. AdaptiveAvgPool2d(1)
随机推荐
pytorch中的双线性插值上采样(Bilinear Upsampling)、F.upsample_bilinear
E15 solution for cx5120 controlling Huichuan is620n servo error
JUC learning
4、【WebGIS实战】软件操作篇——数据导入及处理
多元线性回归
Test function in pychram
Md5sum operation
Avalanche problem and the use of sentinel
家居网购项目
Leetcode 31 next spread, leetcode 64 minimum path sum, leetcode 62 different paths, leetcode 78 subset, leetcode 33 search rotation sort array (modify dichotomy)
TEC: Knowledge Graph Embedding with Triple Context
Filter
How do I use Google Chrome 11's Upload Folder feature in my own code?
pytorch nn. AdaptiveAvgPool2d(1)
【伸手党福利】开发人员重装系统顺序
【EI会议】2022年第三届纳米材料与纳米技术国际会议(NanoMT 2022)
Processing of menu buttons on the left and contents on the right of the background system page, and double scrolling appears on the background system page
串口接收数据方案设计
【伸手党福利】JSONObject转String保留空字段
过滤器 Filter