250x250
반응형
Notice
Recent Posts
Recent Comments
Link
N
(Leet Code JS)DI String Match 본문
728x90
반응형
https://leetcode.com/problems/di-string-match/
DI String Match - 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
투포인터 알고리즘 적용.
답을 리턴할 배열 answer을 선언.
front와 back을 이용해 답을 찾을 것이다.
front = 0, back = s.length으로 선언한 후 for문 진행.
만약 현재 문자가 "I"라면 front++를 answer에 push.
그렇지 않고 "D"라면 back--를 answer에 push.
for문이 끝나면 front와 back을 비교하여, front가 back 보다 작거나 같다면 front를 넣어주고, 그렇지 않다면 back을 넣어서 리턴하면 된다.
const diStringMatch = (s) => {
const answer = [];
let front = 0;
let back = s.length;
for(let i = 0; i < s.length; i++){
if(s[i] === "I"){
answer.push(front++);
} else{
answer.push(back--);
}
}
answer.push(front <= back ? front : back);
return answer;
};
728x90
반응형
'Leet Code 알고리즘' 카테고리의 다른 글
(Leet Code JS) Populating Next Right Pointers in Each Node (0) | 2022.03.02 |
---|---|
(Leet Code JS)Triangle (0) | 2022.03.01 |
(Leet Code JS)Lemonade Change (0) | 2022.02.28 |
(Leet Code JS)Can Place Flowers (0) | 2022.02.25 |
(Leet Code JS)Assign Cookies (0) | 2022.02.25 |