Longest Palindrome问题及解法
来源:互联网 发布:淘宝网人民法院拍卖 编辑:程序博客网 时间:2024/06/08 07:34
问题描述:
Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
This is case sensitive, for example
Note:
Assume the length of given string will not exceed 1,010.
示例:
nput:"abccccdd"Output:7Explanation:One longest palindrome that can be built is "dccaccd", whose length is 7.
问题分析:
本题主要是从给定的字母里选出一部分组成最长的回文串。转换一下,就是相当于把里面出现偶数次的字母出现次数加起来,然后再把里面出现奇数次的字母出现次数减一后再相加,等到sum。若是给定的字母中字母出现次数有奇数次,那么sum = sum + 1.最终返回sum即可。
过程详见代码:
class Solution {public: int longestPalindrome(string s) { vector<int> mapping(256,0); for(int i = 0;i < s.length(); i++) { mapping[s[i]]++;}int flag = 0;int sum = 0;for(int i = 0;i < 256;i++){int temp = mapping[i];if(temp % 2) {sum += temp - 1;flag = 1;}else sum += temp;}return (flag== 1) ? sum + 1 : sum; }};
0 0
- Longest Palindrome问题及解法
- Palindrome Number问题及解法
- Valid Palindrome问题及解法
- Palindrome Partitioning问题及解法
- Palindrome Linked List问题及解法
- Largest Palindrome Product问题及解法
- Valid Palindrome II问题及解法
- Longest Palindromic Substring问题及解法
- Longest Common Prefix问题及解法
- Longest Uncommon Subsequence I问题及解法
- Longest Harmonious Subsequence问题及解法
- Longest Continuous Increasing Subsequence 问题及解法
- Longest Palindromic Subsequence问题及解法
- Longest Repeating Character Replacement问题及解法
- Longest Univalue Path问题及解法
- Longest Increasing Subsequence问题及解法
- Longest Absolute File Path问题及解法
- Longest Word in Dictionary问题及解法
- 参加“技术峰会”得到的感悟
- LeetCode
- C++实现ATM机
- kafka客户端封装
- 线程池工作机制和原理
- Longest Palindrome问题及解法
- 编码相关问题整理
- 模拟时间片轮转算法(C++)
- JavaScript基础
- vs2010添加外部头文件
- invokevirtual、invokespecial、invokestatic、invokeinterface、invokedynamic介绍
- 单例模式
- Binary Watch问题及解法
- 安卓开发中将activity设成translucent导致输入法遮挡edittext,windowSoftInputMode设置无效问题