Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- to-do
- TODOLIST
- 취업준비
- 대학생
- JS
- 다해요
- leetcode
- N-ary Tree Preorder Traversal
- 코딩테스트
- orcle
- lab03-03.exe
- 토이프로젝트
- 마을짓기
- 리버싱
- dualtable
- 균형이진트리
- toVillage
- 사이버보안
- 투두리스트
- 투빌리지
- 악성코드분석
- 자바스크립트
- JavaScript
- 릿코드
- Practicalmalwareanalysis
- 가차시스템
- 악코분
- 듀얼테이블
- gamification
- 사이드프로젝트
Archives
- Today
- Total
이것저것
409. Longest Palindrome 본문
https://leetcode.com/problems/longest-palindrome/description
Longest Palindrome - LeetCode
Can you solve this real interview question? Longest Palindrome - 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,
leetcode.com
문제
문제 해석
소문자 또는 대문자로 구성된 문자열을 지정할 경우 해당 문자로 작성할 수 있는 가장 긴 palindrome의 길이를 반환합니다.
문자는 대소문자를 구분합니다. 예를 들어, "Aa"는 여기서 유사체로 간주되지 않습니다.
정답 코드
let countChar = (string, c) => {
let count;
let array = Array.from(string);
count = array.reduce((cnt, element) => cnt + (c === element), 0);
return count;
}
let longestPalindrome = (s) => {
let map = new Map();
let longestLength = 0;
let numbersOfOdd = 0;
let count = 0;
if(s.length === 1)
return s.length;
console.log(countChar(s, 'a'));
for(let char of s)
map.set(char, countChar(s, char));
for(let value of map.values()) {
if(map.size === 1)
return value;
if(value % 2 === 0)
longestLength += value;
else if (value % 2 === 1) {
if(count === 0) {
longestLength += value;
count = 1;
}
else if(count === 1 || value >= 3) {
longestLength += (value - 1);
}
else if(count === 1 || value === 1)
numbersOfOdd = 1;
}
}
return longestLength + numbersOfOdd;
};
풀이까지의 사고과정
1. 첫번째 트라이
2. 두번째 트라이
3. 세번째 트라이
4. 네번째 트라이
5. 다섯번째 제출
참고자료
- palindrome이란
'코딩테스트 > leetcode' 카테고리의 다른 글
[860] Lemonade Change (0) | 2024.08.15 |
---|---|
[40] Combination Sum II (푸는 중) (0) | 2024.08.13 |
589. N-ary Tree Preorder Traversal (0) | 2023.04.02 |
142. Linked List Cycle II (0) | 2023.03.31 |