# leetcode解題:(Easy) 409. Longest Palindrome 題目:[https://leetcode.com/problems/longest-palindrome/](https://leetcode.com/problems/longest-palindrome/) 描述:給一串包含大小寫字母的字串,找出使用這個字串中的字元所能排出的最長的回文長度,大小寫要區分為不同的字元 解題思路:要讓回文增長需要相同的2個字母,所以只要用Set紀錄出現過的字母,出現2次時就讓回文長度+2,最後因為回文正中間能夠額外有一個單獨的字母,要再判斷有沒有剩餘的多的字母能讓回文長度再+1 程式碼: ```JAVA= class Solution { public int longestPalindrome(String s) { HashSet<Character> set = new HashSet<Character>(); int result = 0; for(int i = 0; i < s.length(); i++) { if(set.contains(s.charAt(i))) { set.remove(s.charAt(i)); result += 2; } else { set.add(s.charAt(i)); } } if(!set.isEmpty()) result++; return result; } } ``` 時間複雜度:O(n) 空間複雜度:O(n) ###### tags: `leetcode` `easy` `map/set`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up