You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them.
We repeatedly make duplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique.
Example 1:
Input: s = "abbaca"
Output: "ca"
Explanation:
For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".
Example 2:
Input: s = "azxxzy"
Output: "ay"
나의 풀이
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
/**
* @param {string} s
* @return {string}
*/
var removeDuplicates = function(s) {
q = [] //b a
for (let c of s) {
console.log(c)
if (q.length !== 0 && c === q[0])
q.shift()
else
q.unshift(c)
}
return q.reverse().join('')
};
|
cs |
문제를 풀며 느낀 점
- 배열의 중복된 값을 아예 제거하는 문제였는데 먼저 q라는 빈 배열을 생성하였고 for문을 이용해서 s배열의 담긴 인자를 c로 하나하나 순회하였습니다. if문을 이용해서 q의 length가 0이 아니고 인자로 들어온 c의 값이 q의 0번째 인덱스의 값과 같다면 shift() 함수를 이용해서 q의 배열의 제일 앞에 있는 값을 제거하였고, 아니라면 q의 배열에 제일 앞에 unshift() 함수를 이용해서 c를 삽입하였습니다. 그렇게 되면 c 에는 중복이 제거된 값이 거꾸로 나열된 있으므로 return을 할 때는 reverse() 함수를 이용해서 반대로 정렬한 값을 join('') 함수를 이용해서 결합한 문자열을 return 했습니다.
'코딩 테스트 풀이 🛠' 카테고리의 다른 글
[Leet Code - eazy] 1920. Build Array from Permutation (0) | 2023.01.14 |
---|---|
[프로그래머스] 콜라츠 추측 (0) | 2023.01.11 |
[LeetCode - mideum] 1689. Partitioning Into Minimum Number Of Deci-Binary Numbers (0) | 2023.01.08 |
[프로그래머스] 최솟값 만들기 (0) | 2023.01.07 |
[프로그래머스] 최댓값과 최솟값 (0) | 2023.01.07 |