一道数组去重的算法题把我整不会了 :: labuladong的算法小抄 #1067
Replies: 9 comments 1 reply
-
数组去重的那道题目(leetcode316)可以仅从贪心的角度解决,无需借助单调栈: 代码:(leetcode执行通过) string removeDuplicateLetters(string s)
{
string r;
vector<deque<int> > ind(26, deque<int>());
int n = s.size();
for (int i = 0; i < n; i++)
ind[s[i] - 'a'].push_back(i);
int cnt = 0;
for (int i = 0; i < 26; i++)
if (!ind[i].empty())
cnt++;
int left_bound = 0;
while (cnt--)
{
int j = 0;
loop:
while (ind[j].empty())
j++;
int index = ind[j].front();
for (int i = index - 1; i >= left_bound; i--)
if (!ind[s[i] - 'a'].empty() && ind[s[i] - 'a'].back() < index)
{
j++;
goto loop;
}
for (int i = index - 1; i >= left_bound; i--)
if (!ind[s[i] - 'a'].empty())
ind[s[i] - 'a'].pop_front();
ind[j].clear();
left_bound = index + 1;
r.push_back(j + 'a');
}
return r;
} |
Beta Was this translation helpful? Give feedback.
-
补充一下:将deque换成queue也是一样的。用goto语句是因为写起来方便,但是的确不是一种好的风格。 |
Beta Was this translation helpful? Give feedback.
-
谢谢回复! |
Beta Was this translation helpful? Give feedback.
-
字典序:对于两个字符串,大小关系取决于两个字符串从左到右第一个不同字符的 ASCII 值的大小关系 |
Beta Was this translation helpful? Give feedback.
-
leetcode 316 CPP版 参考自lc的题解。仅提供思路参考,完全没考虑复杂度。
|
Beta Was this translation helpful? Give feedback.
-
//js版本
var removeDuplicateLetters = function(s) {
if (s.length === 1 || s.length === 0) {
return s
}
const need = new Map()
const count = new Map()
const window = []
let right = 0
for (let i = 0; i < s.length; i++) {
if (!count.has(s[i])) {
count.set(s[i], 1)
} else {
count.set(s[i], count.get(s[i]) + 1)
}
}
while (right < s.length) {
const c = s[right]
right++
if (!need.has(c)) {
if (window.length > 0) {
while (window.length > 0 && window[window.length - 1].charCodeAt(0) > c.charCodeAt(0) && (count.get(window[window.length - 1]) > 1)) {
const del = window.pop()
need.delete(del)
count.set(del, count.get(del) - 1)
}
}
window.push(c)
need.set(c, 1)
} else {
count.set(c, count.get(c) - 1)
}
}
return window.join("")
}; |
Beta Was this translation helpful? Give feedback.
-
打卡,作为一名理科生,太喜欢这种层层逻辑推理的过程了 |
Beta Was this translation helpful? Give feedback.
-
C++ version:
|
Beta Was this translation helpful? Give feedback.
-
文章链接点这里:一道数组去重的算法题把我整不会了
评论礼仪 见这里,违者直接拉黑。
Beta Was this translation helpful? Give feedback.
All reactions