Skip to content

Commit 3abf803

Browse files
committed
add queue and map solve
1 parent 48f2749 commit 3abf803

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

387/step2_2_suggested.cpp

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/*
2+
https://github.com/colorbox/leetcode/pull/29#discussion_r1861430039
3+
を見てそれを参考に自分で書いた解法、比較用
4+
*/
5+
class Solution {
6+
private:
7+
struct CharacterAndCount {
8+
char character;
9+
int index;
10+
};
11+
12+
public:
13+
int firstUniqChar(string s) {
14+
queue<CharacterAndCount> queue;
15+
map<char, int> character_to_count;
16+
for (int i = 0; i < s.size(); i++) {
17+
char c = s[i];
18+
character_to_count[c]++;
19+
queue.push({c, i});
20+
while (true) {
21+
char front_character = queue.front().character;
22+
if (character_to_count[front_character] > 1) {
23+
queue.pop();
24+
} else {
25+
break;
26+
}
27+
}
28+
}
29+
if (queue.empty()) {
30+
return -1;
31+
}
32+
return queue.front().index;
33+
}
34+
};

387/step2_2_suggested_fixed.cpp

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*
2+
step2_2_suggested.cpp
3+
4+
https://github.com/colorbox/leetcode/pull/29#discussion_r1861430039
5+
の書き方に沿って修正したコード、参照用
6+
*/
7+
class Solution {
8+
private:
9+
struct CharacterAndCount {
10+
char character;
11+
int index;
12+
};
13+
14+
public:
15+
int firstUniqChar(string s) {
16+
queue<CharacterAndCount> characters;
17+
map<char, int> character_to_count;
18+
for (int i = 0; i < s.size(); ++i) {
19+
char c = s[i];
20+
++character_to_count[c];
21+
characters.push({c, i});
22+
while (character_to_count[characters.front().character] >= 2) {
23+
characters.pop();
24+
}
25+
}
26+
if (characters.empty()) {
27+
return -1;
28+
}
29+
return characters.front().index;
30+
}
31+
};

0 commit comments

Comments
 (0)