LintCode 最长回文串
来源:互联网 发布:zipalign优化教程 编辑:程序博客网 时间:2024/06/07 05:44
题目
给出一个包含大小写字母的字符串。求出由这些字母构成的最长的回文串的长度是多少。数据是大小写敏感的,也就是说,"Aa" 并不会被认为是一个回文串。 注意事项假设字符串的长度不会超过 1010。样例给出 s = "abccccdd" 返回 7一种可以构建出来的最长回文串方案是 "dccaccd"。
思路
- 先找出不同的字符。
- 然后遍历每个不同字符有多少个。
- 每个字符的个数/2相加的和再乘上2得到len(处理奇数个数)。
- 如果这个len等于字符串的长度,则len就是最大回文长度;否则最大回文长度等于len+1.(就是回文中间位置是否可以加只有一个的字符)
代码
public int longestPalindrome(String s) { // Write your code here char ch[] = s.toCharArray(); Set<Character> set = new HashSet<>(); for (int i = 0; i < s.length(); i++) { set.add(ch[i]); } int a[] = new int[set.size()]; int n = 0; for (Character c : set) { int count = 0; for (int i = 0; i < s.length(); i++) { if (c == ch[i]) { count++; } } a[n] = count; n++; } int sum = 0; for (int i = 0; i < a.length; i++) { sum += a[i] / 2; } //回文中间位置是否可以加只有一个的字符 if (2 * sum < s.length()) { return 2 * sum + 1; } else { return 2 * sum; } }
阅读全文
0 0
- LintCode 最长回文串
- lintcode:最长回文串
- 最长回文串-LintCode
- LintCode-最长回文子串
- LintCode:最长回文子串
- lintcode,最长回文子串
- lintcode(627)最长回文串
- [lintcode]最长回文子串
- lintcode -- 最长回文子串
- LintCode之最长回文串
- 最长回文子串-LintCode
- LintCode 最长回文子串
- lintcode最长回文子串
- lintcode-最长回文子串-200
- LintCode之最长回文子串
- 最长回文字串 lintcode
- **[Lintcode]Longest Palindromic Substring最长回文子串
- LintCode python 小白-简单题-627最长回文串
- spark程序入门-wordCount详解总结
- Balanced Lineup 线段树 rmq 区间最值
- 数据库关于varchar和nvarchar的区别
- 精细化运营时代,金融魔镜如何助力各产品线实现业务增长
- org.xml.sax.SAXParseException异常处理
- LintCode 最长回文串
- 打印回环数字矩阵
- 解决 执行jacocoTestReport生成报告时 报Unable to read execution data file coverage.ec
- jsp(java server page)之模板式servlet
- JAVA JNI 数据传递
- ElasticSearch 踩过的坑
- JS 实现对象深度复制
- Hibernate之多对多单向关联(ManyToMany)
- SpringCloud: 服务消费者(rest+ribbon)