# 409. Longest Palindrome (Easy)

## 1.問題

* 給予一個由大小寫字母組成的string, 找出可以組成的最長迴文字串

![](/files/-LI-OU67NPQuY3QX_HIc)

## 2.想法&#x20;

* 統計每個字母出現的次數
  * 出現一次者
  * 出現兩次者
* 將字元轉為int來統計

```
vector<int> sv(59, 0);
for(int i = 0 ; i < (int)s.size(); i++){
        sv[(int)(s[i] - 'A')]++;
}
```

## 3.程式碼

```
class Solution {
public:
    int longestPalindrome(string s) {
        vector<int> sv(59, 0);
        for(int i = 0 ; i < (int)s.size(); i++){
            sv[(int)(s[i] - 'A')]++;
        }
        int pairCount = 0;
        int singleCount = 0;
        for(int i = 0 ; i < 59; i++){
            while(sv[i] != 0 && sv[i] != 1 ){
                sv[i] = sv[i] - 2;
                pairCount += 2;
            }
            if(sv[i] == 1){
                singleCount++;
            }
        }
        return singleCount > 0 ? pairCount + 1 : pairCount;
    }
};
```

## 4.Performance

![](/files/-LI-PUiiTD-sliiAogkw)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jenhsuan.gitbook.io/algorithm/leetcode/409.-longest-palindrome-easy.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
