LeetCode-Longest_Palindrome

题目:

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 "Aa" is not considered a palindrome here.

Note:
Assume the length of given string will not exceed 1,010.

Example:

Input:
"abccccdd"

Output:
7

Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.


翻译:

给定一个包含小写和大写字母的字符串,找到可以利用这些字母组成最长回文串的长度。

这是大小写敏感的,举例 "Aa" 在这里被考虑为不是回文的。

注意:

假设给定字符串的长度不会超过1,010。

例子:

输入:
"abccccdd"

输出:
7

解释:
一个最长的回文串可以被创建为"dccaccd",它的长度为7。


思路:

首先用一个map函数记录每个字母出现的个数,然后,对map中的每一个字母出现的个数进行判断。由于回文串的个数分为奇数("abcba")和偶数("abba")两种,因此,为了方便判断最后回文串的个数是奇是偶,利用一个巧妙的设定mid=false来判断是否有字母个数为奇数,首先将每一个字母的个数加到结果result中,若map中的一个字母个数不为偶,那么result-1,同时mid=true,来证明字母中有奇数个的出现,这样一来,在所有字母个数判定结束的时候,通过mid来决定result最后是否要加入1,若map中的字母都是偶数,即mid=false,则result不必加1,否则,若mid=true,说明map中的字母有奇数个,此时可以构成奇数回文数,则result加1。


C++代码(Visual Studio 2017):

#include "stdafx.h"
#include <iostream>
#include <string>
#include <map>
using namespace std;

class Solution {
public:
	int longestPalindrome(string s) {
		int result=0;
		bool mid=false;
		map<char, int> m;
		for (int i = 0; i < s.size(); i++) {
			m[s[i]]++;
		}
		map<char, int>::iterator it;  
		for (it = m.begin(); it != m.end(); it++) {
			result += it->second;
			if (it->second % 2 == 1) {
				result -= 1;
				mid = true;
			}
		}
		return mid ? result + 1 : result;
	}
};

int main()
{
	Solution s;
	string str="bb";
	int result;
	result = s.longestPalindrome(str);
	cout << result;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/tel_annie/article/details/80310282
今日推荐