반응형
목차
문제
Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.
Letters are case sensitive, for example, "Aa" is not considered a palindrome here.
Example 1:
Input: s = "abccccdd"
Output: 7
Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7.
Example 2:
Input: s = "a"
Output: 1
Explanation: The longest palindrome that can be built is "a", whose length is 1.
Constraints:
- 1 <= s.length <= 2000
- s consists of lowercase and/or uppercase English letters only.
풀이
class Solution {
public int longestPalindrome(String s) {
int result = 0;
if(s.length() == 0 || s.length() == 1){
return s.length();
}
HashSet<Character> hs = new HashSet<Character>();
for (int i = 0; i<s.length(); i++){
if(hs.contains(s.charAt(i))){
hs.remove(s.charAt(i));
result++;
}else{
hs.add(s.charAt(i));
}
}
if(hs.size()>0){
return result*2 + 1;
}
return result*2;
}
}
반응형
'코딩테스트 > 알고리즘 문제풀이' 카테고리의 다른 글
[JAVA] K번째수 (0) | 2022.11.11 |
---|---|
[JAVA] 326. Power of Three (0) | 2022.11.09 |
[JAVA] 121. Best Time to Buy and Sell Stock (0) | 2022.11.08 |
[JAVA] 다음에 올 숫자 (0) | 2022.11.07 |
[MySQL] 과일로 만든 아이스크림 고르기 (0) | 2022.11.06 |
댓글