1. 程式人生 > >lintcode 627 最長迴文串Python版本

lintcode 627 最長迴文串Python版本

Cottbuser 灣區人工智慧 今天

作者:Cottbuser 會多國語言的海歸  公眾號:灣區人工智慧 微博:灣區人工智慧 知乎:灣區人工智慧 AI QQ群:604562980 一線人工智慧工程師獨立兼職運營 如果本文對你有幫助,歡迎點贊,轉發

資料結構和演算法分析是程式設計師面試必考內容,接下來打算刷常見面試題,順便分享給大家。刷,刷,刷,一般刷題300道,刷3遍,國內大部分公司offer隨便拿。普通程式設計師刷完中級題目就夠了,想進頂級網際網路公司,要刷高階題目,想節省時間,可以報個培訓班。我個人推薦不差錢的可以報培訓班提高效率。

今天題目:

627 最長迴文串 描述 給出一個包含大小寫字母的字串。求出由這些字母構成的最長的迴文串的長度是多少。

資料是大小寫敏感的,也就是說,"Aa" 並不會被認為是一個迴文串。

假設字串的長度不會超過 1010。

您在真實的面試中是否遇到過這個題?   樣例 給出 s = "abccccdd" 返回 7

一種可以構建出來的最長迴文串方案是 "dccaccd"。 627 Longest Palindrome Description 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.

Assume the length of given string will not exceed 1010.

Have you met this question in a real interview?   Example Given s = "abccccdd" return 7

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

內容目錄

Python版本java版本C++版本

Python版本

class Solution:
    # @param {string} s a string which consists of lowercase or uppercase letters
    # @return {int} the length of the longest palindromes that can be built
    def longestPalindrome(self, s):
        # Write your code here
        hase_set = {}
        #
        #避免hash_set裡面有重複,並且建立一個鍵值對,鍵就是s裡面的字母,值就是true
        for c in s: #去掉s裡面出現偶數次的字母,只保留奇數字母
            if c in hase_set:
                del hase_set[c]
            else:
                hase_set[c] = True  #這裡的true可以換成任何東西
        print(hase_set)
        remove = len(hase_set)  #所有奇數個字母的長度
        if remove > 0: 
            remove -= 1 #要留一個字母作為迴文串中間的字母

        return len(s) - remove  #如果雜湊表裡有元素,只留一個作為迴文串最中間的字母就行。

my_solution = Solution()
s = "fabccccdd"
result = my_solution.longestPalindrome(s)
print(result)

java版本

/**
* 本參考程式來自九章演算法,由 @九章演算法 提供。版權所有,轉發請註明出處。
* - 九章演算法致力於幫助更多中國人找到好的工作,教師團隊均來自矽谷和國內的一線大公司在職工程師。
* - 現有的面試培訓課程包括:九章演算法班,系統設計班,演算法強化班,Java入門與基礎演算法班,Android 專案實戰班,
* - Big Data 專案實戰班,演算法面試高頻題班, 動態規劃專題班
* - 更多詳情請見官方網站:http://www.jiuzhang.com/?source=code
*/ 

// version 1
public class Solution {
    /**
     * @param s a string which consists of lowercase or uppercase letters
     * @return the length of the longest palindromes that can be built
     */
    public int longestPalindrome(String s) {
        // Write your code here
        Set<Character> set = new HashSet<>();
        for (char c : s.toCharArray()) {
            if (set.contains(c)) set.remove(c);
            else set.add(c);
        }

        int remove = set.size();
        if (remove > 0)
            remove -= 1;
        return s.length() - remove;
    }
}

// version 2
public class Solution {
    public int longestPalindrome(String s) {
        int[] charStatArray = new int[52];
        int oneTimeOddCount = 0;
        int evenCount = 0;

        // zero clearing of the array
        //memset(charStatArray, 0, sizeof(charStatArray));

        // keep the times of appearance of each character in the array
        for (char ch: s.toCharArray()) {
            if (ch >= 97) {
                charStatArray[26 + ch - 'a']++;
            }
            else {
                charStatArray[ch - 'A']++;
            }
        }

        // the answer is the count of characters that has even number of appereances.
        // for characters that has odd number of appereances,
        // their appereances minus 1 will make their apperances even.
        // And finally we can put an unused character in the middle of the palindrome
        // (if there is any).
        for (int cnt: charStatArray) {
            if (cnt != 0) {
                if (cnt % 2 == 0) {
                    evenCount += cnt;
                } else {
                    if (cnt == 1) {
                        oneTimeOddCount++;
                    }
                    else {
                        evenCount += cnt - 1;
                        oneTimeOddCount++;
                    }
                }
            }
        }

        return oneTimeOddCount > 0 ? 1 + evenCount : evenCount;
    }
}

C++版本

/**
* 本參考程式來自九章演算法,由 @九章演算法 提供。版權所有,轉發請註明出處。
* - 九章演算法致力於幫助更多中國人找到好的工作,教師團隊均來自矽谷和國內的一線大公司在職工程師。
* - 現有的面試培訓課程包括:九章演算法班,系統設計班,演算法強化班,Java入門與基礎演算法班,Android 專案實戰班,
* - Big Data 專案實戰班,演算法面試高頻題班, 動態規劃專題班
* - 更多詳情請見官方網站:http://www.jiuzhang.com/?source=code
*/ 

class Solution {
public:
    int longestPalindrome(string s) {
        int charStatArray[52];
        int oneTimeOddCount = 0;
        int evenCount = 0;

        // zero clearing of the array
        memset(charStatArray, 0, sizeof(charStatArray));

        // keep the times of appearance of each character in the array
        for (char ch: s) {
            if (ch >= 97) {
                charStatArray[26 + ch - 'a']++;
            }
            else {
                charStatArray[ch - 'A']++;
            }
        }

        // the answer is the count of characters that has even number of appereances.
        // for characters that has odd number of appereances,
        // their appereances minus 1 will make their apperances even.
        // And finally we can put an unused character in the middle of the palindrome
        // (if there is any).
        for (int cnt: charStatArray) {
            if (cnt != 0) {
                if (cnt % 2 == 0) {
                    evenCount += cnt;
                } else {
                    if (cnt == 1) {
                        oneTimeOddCount++;
                    }
                    else {
                        evenCount += cnt - 1;
                        oneTimeOddCount++;
                    }
                }
            }
        }

        return oneTimeOddCount > 0 ? 1 + evenCount : evenCount;
    }
};
print_r('點個贊吧');
var_dump('點個贊吧');
NSLog(@"點個贊吧!")
System.out.println("點個贊吧!");
console.log("點個贊吧!");
print("點個贊吧!");
printf("點個贊吧!");
cout << "點個贊吧!" << endl;
Console.WriteLine("轉發一下吧!");
fmt.Println("轉發一下吧!")
Response.Write("轉發一下吧!");
alert(’轉發一下吧!’)

認識你是我們的緣分,同學,等等,記得關注我。

微信掃一掃 關注該公眾號