Open seungriyou opened 4 months ago
https://leetcode.com/problems/longest-happy-string/ similar to #70
마찬가지로 greedy 방식으로 접근한다.
cnt 값이 0이 아닌 것에 대해서 priority queue [(-cnt, char)] 구성 (max heap)
cnt
[(-cnt, char)]
priority queue를 이용하여 limit이 가장 높은 문자 ch1 pop
ch1
res에 가장 최근 추가된 두 문자와 ch1이 같다면,
res
limit이 두 번째로 높은 문자 ch2 pop
ch2
➡️ 이때, priority queue가 비어있다면, 현재의 res를 곧바로 return
ch2를 res에 추가하고, cnt2 업데이트하여 (0이 아니면) priority queue에 다시 넣기
cnt2
ch1은 그대로 다시 priority queue에 넣기
3번에 해당하지 않는다면 ch1을 res에 추가하고, cnt1 업데이트하여 (0이 아니면) priority queue에 다시 넣기
cnt1
res 반환
O(nlog3)
O(n)
pq
O(1)
Approach
마찬가지로 greedy 방식으로 접근한다.
cnt
값이 0이 아닌 것에 대해서 priority queue[(-cnt, char)]
구성 (max heap)priority queue를 이용하여 limit이 가장 높은 문자
ch1
popres
에 가장 최근 추가된 두 문자와ch1
이 같다면,limit이 두 번째로 높은 문자
ch2
popch2
를res
에 추가하고,cnt2
업데이트하여 (0이 아니면) priority queue에 다시 넣기ch1
은 그대로 다시 priority queue에 넣기3번에 해당하지 않는다면
ch1
을res
에 추가하고,cnt1
업데이트하여 (0이 아니면) priority queue에 다시 넣기res
반환Complexity
O(nlog3)
=O(n)
O(n)
(res
는 결과 반환에 사용되므로pq
만 고려해서O(1)
이라고 해도 되나..?)