当前位置:网站首页>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
边栏推荐
- 网页不能右键 F12 查看源代码解决方案
- 深度学习中的随机种子torch.manual_seed(number)、torch.cuda.manual_seed(number)
- Introduction to EtherCAT
- multiple linear regression
- Leetcode:829. Sum of continuous integers
- Ultimate dolls 2.0 | encapsulation of cloud native delivery
- 【EI检索】2022年第六届材料工程与先进制造技术国际会议(MEAMT 2022)重要信息会议网址:www.meamt.org会议时间:2022年9月23-25日召开地点:中国南京截稿时间:2
- bootsrap中的栅格系统
- Explain spark operation mode in detail (local+standalone+yarn)
- shell脚本使用两个横杠接收外部参数
猜你喜欢

ASGNet论文和代码解读2

LeetCode 31下一个排列、LeetCode 64最小路径和、LeetCode 62不同路径、LeetCode 78子集、LeetCode 33搜索旋转排序数组(修改二分法)

Leetcode 128 longest continuous sequence (hash set)

RSN:Learning to Exploit Long-term Relational Dependencies in Knowledge Graphs

pytorch中的双线性插值上采样(Bilinear Upsampling)、F.upsample_bilinear

Learning notes for introduction to C language multithreaded programming

Sort linked list (merge sort)

FCN全卷積網絡理解及代碼實現(來自pytorch官方實現)

Error: plug ins declaring extensions or extension points must set the singleton directive to true

Pyramid Scene Parsing Network【PSPNet】论文阅读
随机推荐
Pyramid scene parsing network [pspnet] thesis reading
BluePrism注册下载并安装-RPA第一章
Nacos
leetcode 1818 绝对值,排序,二分法,最大值
Appium fundamentals of automated testing - basic principles of appium
Keil5中如何做到 0 Error(s), 0 Warning(s).
Edge drawing: a combined real-time edge and segment detector
5、【WebGIS实战】软件操作篇——服务发布及权限管理
衡量两个向量相似度的方法:余弦相似度、pytorch 求余弦相似度:torch.nn.CosineSimilarity(dim=1, eps=1e-08)
torch. histc
Depth first traversal of C implementation Diagram -- non recursive code
Cygwin的下载和安装配置
复习专栏之---消息队列
RSN:Learning to Exploit Long-term Relational Dependencies in Knowledge Graphs
FCN全卷积网络理解及代码实现(来自pytorch官方实现)
How do I use Google Chrome 11's Upload Folder feature in my own code?
The difference between MFC for static libraries and MFC for shared libraries
访问阿里云存储的图片URL实现在网页直接预览略缩图而不直接下载
C语言的sem_t变量类型
JS日常开发小技巧(持续更新)