1.문제
Given a string of English letters s, return the greatest English letter which occurs as both a lowercase and uppercase letter in s. The returned letter should be in uppercase. If no such letter exists, return an empty string.
An English letter b is greater than another letter a if b appears after a in the English alphabet.
문자열 s가 주어질 때 s에 같은 알파벳 소문자 , 대문자가 모두 존재하는 알파벳을 대문자의 형태로 리턴하는 문제이다.
만약 소문자, 대문자가 모두 존재하는 알파벳이 하나 이상이라면 사전 순서상 가장 뒤에 위치하는 알파벳을 리턴하면 된다.
Example 1
Input: s = "lEeTcOdE"
Output: "E"
Explanation:
The letter 'E' is the only letter to appear in both lower and upper case.
Example 2
Input: s = "arRAzFif"
Output: "R"
Explanation:
The letter 'R' is the greatest letter to appear in both lower and upper case.
Note that 'A' and 'F' also appear in both lower and upper case, but 'R' is greater than 'F' or 'A'.
Example 3
Input: s = "AbCdEfGhIjK"
Output: ""
Explanation:
There is no letter that appears in both lower and upper case.
Constraints:
- 1 <= s.length <= 1000
- s consists of lowercase and uppercase English letters.
2.풀이
- s를 순회하면서 현재 알파벳이 대문자인지 소문자인지 체크한다.
- 현재 문자가 대문자라면 s에 같은 알파벳 소문자가 있는지 체크한다.
- 현재 문자가 소문자라면 s에 같은 알파벳 대문자가 있는지 체크한다.
- 존재한다면 result에 대문자를 push한다.
- result를 사전 정렬한다.
- result의 마지막 요소가 있으면 마지막 요소를, 없으면 ""를 리턴한다.
/**
* @param {string} s
* @return {string}
*/
const greatestLetter = function (s) {
const result = [];
for (let i = 0; i < s.length; i++) {
// 만약 소문자라면 s 에 같은 알파벳의 대문자가 존재하는지 체크해서 존재한다면 대문자를 result에 push
if (s[i].charCodeAt() > 90) {
if (s.includes(String.fromCharCode(s[i].charCodeAt() - 32))) {
result.push(String.fromCharCode(s[i].charCodeAt() - 32));
}
// 만약 대문자라면 s에 같은 알파벳의 소문자가 존재하는지 체크해서 존재한다면 대문자를 result 에 push
} else if (s[i].charCodeAt() <= 90) {
if (s.includes(String.fromCharCode(s[i].charCodeAt() + 32))) {
result.push(String.fromCharCode(s[i].charCodeAt()));
}
}
}
// result를 오름차순 정렬한다.
result.sort();
// result의 마지막 요소가 존재하면 리턴 , 아니라면 빈 공백 리턴
return result.pop() ? result.pop() : "";
};
3.결과
