leetcode_409. 最长回文串
2022/3/4 23:45:11
本文主要是介绍leetcode_409. 最长回文串,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
给定一个包含大写字母和小写字母的字符串 s ,返回 通过这些字母构造成的 最长的回文串 。
在构造过程中,请注意 区分大小写 。比如 "Aa" 不能当做一个回文字符串。
示例 1:
输入:s = "abccccdd"
输出:7
解释:
我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。
int longestPalindrome(char * s){ int len = strlen(s); int *hash = (int *)malloc(sizeof(int) * 100); memset(hash, 0, sizeof(int) * 100) ; int res = 0; for(int i = 0; i < len; i++) { // 一开始 用的 - ‘a’ 出现错误 hash[s[i] - '0']++; } int flag = 0; int tmp = 0; for(int i = 0; i < 100; i++) { if(hash[i] % 2 == 0) { res += hash[i]; } else { flag = 1; tmp = hash[i] / 2; res += tmp * 2 ; } } if(flag == 1) { res += 1; } return res; }
上面自己写的。 看下标准答案
1 int longestPalindrome(char * s){ 2 int slen = strlen(s); 3 if(slen == 0) { 4 return NULL; 5 } 6 if(slen == 1) { 7 return 1; 8 } 9 int *hash = (int *)malloc(sizeof(int) * 128); 10 memset(hash, 0, sizeof(int) * 128); 11 12 for(int i = 0; i < slen; i++) { 13 hash[s[i]]++; 14 } 15 int res = 0; 16 for(int i = 0; i < 128; i++) { 17 res += hash[i] - hash[i]%2; // 很精妙 ,这句话 18 } 19 if(res < slen) { 20 return res + 1; 21 }else { 22 return res; 23 } 24 }
这篇关于leetcode_409. 最长回文串的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-07-06有没有什么开源的py项目可以对图像进行分类-icode9专业技术文章分享
- 2024-07-05feign默认connecttimeout和readtimeout是多少-icode9专业技术文章分享
- 2024-07-05idea控制台,日志太多,导致部分想看得日志被刷走 搜不到-icode9专业技术文章分享
- 2024-07-05The server selected protocol version Tls10 is not accepted by client preferences [TLs12]-icode9专业技术文章分享
- 2024-07-05怎么清理项目缓存-icode9专业技术文章分享
- 2024-07-04安装 Eyoucms详细图文教程-icode9专业技术文章分享
- 2024-07-04ueditor 复制文章时,图片的链接是一个下载图片地址,该如何处理?-icode9专业技术文章分享
- 2024-07-04怎样判断host有没有对wordpress有缓存呢-icode9专业技术文章分享
- 2024-07-04具有编译功能的系统make后,无法ssh连接-icode9专业技术文章分享
- 2024-07-04make后如何升级ssh-icode9专业技术文章分享