[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.

 

這又是一道關於回文字符串的問題,LeetCode上關於回文串的題有十來道呢,也算一個比較重要的知識點。但是這道題確實不算一道難題,給了我們一個字符串,讓我們找出可以組成的最長的回文串的長度,由於字符順序可以打亂,所以問題就轉化為了求偶數個字符的個數,我們了解回文串的都知道,回文串主要有兩種形式,一個是左右完全對稱的,比如noon, 還有一種是以中間字符為中心,左右對稱,比如bob,level等,那么我們統計出來所有偶數個字符的出現總和,然后如果有奇數個字符的話,我們取取出其最大偶數,然后最后結果加1即可,參見代碼如下:

 

解法一:

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

 

上面那種方法是通過哈希表來建立字符串和其出現次數的映射,這里我們可以換一種思路,來找出搜有奇數個的字符,我們采用的方法是使用一個set集合,如果遍歷到的字符不在set中,那么就將其加入set,如果已經在set里了,就將其從set中刪去,這樣遍歷完成后set中就是所有出現個數是奇數個的字符了,那么我們最后只要用s的長度減去0和set長度減一之間的較大值即可,為啥這樣呢,我們想,如果沒有出現個數是奇數個的字符,那么t的長度就是0,減1成了-1,那么s的長度只要減去0即可;如果有奇數個的字符,那么字符個數減1,就是不能組成回文串的字符,因為回文串最多允許一個不成對出現的字符,參見代碼如下:

 

解法二:

class Solution {
public:
    int longestPalindrome(string s) {
        unordered_set<char> t;
        for (char c : s) {
            if (!t.count(c)) t.insert(c);
            else t.erase(c);
        }
        return s.size() - max(0, (int)t.size() - 1);
    }
};

 

最后這種方法利用到了STL中的count函數,就是找字符串中某個字符出現的個數,那么我們和1相與,就可以知道該個數是奇數還是偶數了,返回的寫法和上面那種方法相同,參見代碼如下:

 

解法三:

class Solution {
public:
    int longestPalindrome(string s) {
        int odds = 0;
        for (char c = 'A'; c <= 'z'; ++c) {
            odds += count(s.begin(), s.end(), c) & 1;
        }
        return s.size() - max(0, odds - 1);
    }
};

 

類似題目:

Palindrome Pairs

Palindrome Permutation II

Palindrome Permutation

Palindrome Linked List

Shortest Palindrome

Palindrome Partitioning II

Palindrome Partitioning

Valid Palindrome

Palindrome Number

Longest Palindromic Substring

 

參考資料:

https://discuss.leetcode.com/topic/61338/what-are-the-odds-python-c

https://discuss.leetcode.com/topic/61574/very-easy-to-understand-java-solution

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM