250x250
반응형
Notice
Recent Posts
Recent Comments
Link
N
(Leet Code JS)Letter Case Permutation 본문
728x90
반응형
https://leetcode.com/problems/letter-case-permutation/
Letter Case Permutation - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
백트랙킹 활용.
dfs() 함수에 s와 시작 인덱스 0을 넘겨 시작한다.
만약 i === s.length와 같다면 answer에 지금까지 진행한 문자열 s를 넣고 종료한다.
그렇지 않다면 계속 문자열을 탐색한다.
현재 i번째 인덱스가 문자라면 대문자로 바꾸거나 소문자로 바꿔서 answer에 넣어야 한다.
if문을 통해 대소문자를 구분하고,
front와 back에는 0 ~ i / i + 1 ~ s.length에 해당하는 문자열을 저장한다.
또한, 각 조건에 맞게 s[i]를 대->소, 소->대 문자로 바꿔서 dfs(front + char + back, i + 1)을 넘겨주면 된다.
const letterCasePermutation = (s) => {
const answer = [];
const dfs = (s, i) => {
if(i === s.length){
answer.push(s);
return;
}
dfs(s, i + 1);
if(s[i] >= "a" && s[i] <= "z"){
const front = s.slice(0, i);
const back = s.slice(i + 1);
const upper = s[i].toUpperCase();
dfs(front + upper + back, i + 1);
} else if(s[i] >= "A" && s[i] <= "Z"){
const front = s.slice(0, i);
const back = s.slice(i + 1);
const lower = s[i].toLowerCase();
dfs(front + lower + back, i + 1);
}
}
dfs(s, 0);
return answer;
};
728x90
반응형
'Leet Code 알고리즘' 카테고리의 다른 글
(Leet Code JS)House Robber (0) | 2022.03.14 |
---|---|
(Leet Code JS)Valid Sdoku (0) | 2022.03.11 |
(Leet Code JS)Rotting Oranges (0) | 2022.03.10 |
(Leet Code JS)Best Time to Buy and Sell Stock (0) | 2022.03.08 |
(Leet Code JS)Permutation in String (0) | 2022.03.08 |