当前位置:网站首页>LeetCode_409_最长回文串
LeetCode_409_最长回文串
2022-07-28 03:36:00 【Fitz1318】
题目链接
题目描述
给定一个包含大写字母和小写字母的字符串 s ,返回 通过这些字母构造成的 最长的回文串 。
在构造过程中,请注意 区分大小写 。比如 "Aa" 不能当做一个回文字符串。
示例 1:
输入:s = "abccccdd"
输出:7
解释:
我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。
示例 2:
输入:s = "a"
输入:1
示例 3:
输入:s = "bb"
输入: 2
提示:
1 <= s.length <= 2000
s 只能由小写和/或大写英文字母组成
解题思路
- 遍历字符串,并使用HashSet来记录,如果没有出现过则保存在set中,如果出现过了,那么就将这个出现过的字母从set中删除,并将答案+2
- 最后set中存放的都是奇数个的字母,判断一下set集合是否为空,如果不为空,就将答案+1
AC代码
class Solution {
public int longestPalindrome(String s) {
int ans = 0;
HashSet<Character> set = new HashSet<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (set.contains(c)) {
set.remove(c);
ans += 2;
} else {
set.add(c);
}
}
if (set.size() > 0) {
ans += 1;
}
return ans;
}
}
边栏推荐
- 高等数学(第七版)同济大学 习题3-4 个人解答(后8题)
- Outlook tutorial, how to use color categories and reminders in outlook?
- Unity backpack system
- 20220726汇承科技的蓝牙模块HC-05的AT命令测试
- How to arrange PCB screen printing? Please check this manual!
- Tungsten Fabric SDN — BGP as a Service
- Leetcode skimming: dynamic programming 08 (segmentation and subsets)
- Leetcode 29th day
- How to make the Internet access the intranet IP (used by esp8266 web pages)
- Prefix-Tuning: Optimizing Continuous Prompts for Generation
猜你喜欢

C language to achieve a dynamic version of the address book

Mouse operation and response

How to uninstall clean ZABBIX service? (super detailed)

95后阿里P7晒出工资单:真的是狠狠扎心了...

An article grasps the calculation and processing of date data in PostgreSQL

【LeetCode】34、在排序数组中查找元素的第一个和最后一个位置
![[5g NR] RRC reject analysis](/img/51/fc39804b39a9014be3130c09e5444c.png)
[5g NR] RRC reject analysis

Outlook 教程,如何在 Outlook 中使用颜色类别和提醒?

每周推荐短视频:如何正确理解“精益”这个词?

Unity simply implements the dialog function
随机推荐
Push chart written by helm to harbor warehouse
What is tor? What is the use of tor browser update?
leetcode刷题:动态规划08(分割等和子集)
Unity简单实现对话功能
"Xiaodeng" network equipment monitoring in operation and maintenance
MSGAN用于多种图像合成的模式搜索生成对抗网络---解决模式崩塌问题
服务器内存故障预测居然可以这样做!
Mouse operation and response
某宝模拟登录,减少二次验证的方法
动态规划——509. 斐波那契数
How to make the Internet access the intranet IP (used by esp8266 web pages)
动态规划——1049. 最后一块石头的重量 II
How to solve MySQL deep paging problem
203.移除链表元素
2022 summary of the latest Android handler related interview questions
Responsive high-end website template source code Gallery material resource download platform source code
Unity背包系统
Volvo: what on earth does the deep-rooted "sense of security" rely on?
ASEMI整流桥GBPC5010,GBPC5010参数,GBPC5010大小
Swift中的协议