1.문제
Given a string s, reverse the string according to the following rules:
- All the characters that are not English letters remain in the same position.
- All the English letters (lowercase or uppercase) should be reversed.
Return s after reversing it.
문자열 s가 주어질 때 알파벳이면 반대 순서로 정렬하고 알파벳이 아니면 순서를 바꾸지 않은 새로운 문자열을 리턴하는 문제이다.
Example 1
Input: s = "ab-cd"
Output: "dc-ba"
Example 2
Input: s = "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"
Example 3
Input: s = "Test1ng-Leet=code-Q!"
Output: "Qedo1ct-eeLg=ntse-T!"
Constraints:
- 1 <= s.length <= 100
- s consists of characters with ASCII values in the range [33, 122].
- s does not contain '\"' or '\'.
2.풀이
- s를 거꾸로 for 문을 돌면서 알파벳이면 reverse 배열에 넣어준다.
- s의 길이만큼 반복문을 돌면서 s[i]가 알파벳이면 reverse에서 해당 인덱스의 알파벳을 result에 더한다.
- s[i]가 알파벳이 아니면 바로 s[i]를 result에 더한다.
/**
* @param {string} s
* @return {string}
*/
const reverseOnlyLetters = function (s) {
const regex = /^[a-zA-Z]$/;
const reverse = [];
let result = "";
let index = 0;
// 알파벳이면 reverse 배열에 넣어준다.
for (let i = s.length - 1; i >= 0; i--) {
if (regex.test(s[i])) {
reverse.push(s[i]);
}
}
for (let i = 0; i < s.length; i++) {
if (regex.test(s[i])) {
// 알파벳이면 reverse 배열에서 꺼내서 result에 더하고 인덱스 1 증가
result += reverse[index];
index++;
} else {
// 알파벳이아니면 문자를 바로 result 에 더한다
result += s[i];
}
}
return result;
};
3.결과
