LeetCode 409——最長迴文串

1. 題目

2. 解答

我們先來看一看回文子串的規律,如果迴文子串的長度爲偶數,那麼其中所有的每個元素都出現了偶數次;如果迴文子串的長度爲奇數,那麼有一個元素出現了奇數次而其餘每個元素都出現了偶數次。

所以我們需要做的就是遍歷一遍字符串,統計每個元素出現的次數。這裏只有大寫字母和小寫字母,我們用一個大小爲 52 的數組充當散列表即可。

最後我們就可以得出偶數的元素有多少個,再看看有沒有多餘的一個奇數元素就得到了能組成的最長迴文序列。

int longestPalindrome(string s) {

    int n = s.size();
    if (n == 0) return 0;
    int table[52] = {0};
        
    for (int i = 0; i < n; i++)
    {
        int index = int(s[i] - 'A');
        if (s[i] >= 'a')    index -= 6;
        table[index]++;
    }

    int even = 0;
    int odd = 0;
    for (int i = 0; i < 52; i++)
    {
        even += table[i] / 2 * 2;
        odd += table[i] % 2;     
    }
    
    odd = odd > 0 ? 1: 0;
    return even + odd;
}

獲取更多精彩,請關注「seniusen」!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章