1.문제
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.
주어진 문자열에서 가장 길이가 긴 palindrome의 길이를 리턴하는문제이다. 이때 대소문자 구분을 한다.
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.
2.풀이
- 문자열을 앞에서부터 for문을 돌면서 객체에 문자의 갯수 유무를 체크한다.
- 만약 객체안에 현재 문자값이 들어가 있다면 map[문자] 의 값을 0으로 만들고 sum += 2
- 만약 객체안에 현재 문자값이 없다면 map[문자] = 1
- 만약 sum < s.length 이면 정중앙에 아무 문자 하나를 추가해서 리턴한다.
/**
* @param {string} s
* @return {number}
*/
const longestPalindrome = function (s) {
let sum = 0;
let map = {};
for (let i = 0; i < s.length; i++) {
if (!map[s[i]]) { // map에 s[i] 값이 없으면 갯수 1증가
map[s[i]] = 1;
} else { //있으면 갯수 0으로 만들고 sum += 2
sum += 2;
map[s[i]] = 0;
}
}
return sum < s.length ? sum + 1 : sum; // s길이보다 sum이 작다면 정중앙에 철자 1개 추가해서 리턴
};
3.결과
