Skip to content

Commit 1fdb873

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

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+
public:
7+
int firstUniqChar(string s) {
8+
queue<CharacterAndCount> queue;
9+
map<char, int> character_to_count;
10+
for (int i = 0; i < s.size(); i++) {
11+
char c = s[i];
12+
character_to_count[c]++;
13+
queue.push({c, i});
14+
while (true) {
15+
char front_character = queue.front().character;
16+
if (character_to_count[front_character] > 1) {
17+
queue.pop();
18+
} else {
19+
break;
20+
}
21+
}
22+
}
23+
if (queue.empty()) {
24+
return -1;
25+
}
26+
return queue.front().index;
27+
}
28+
29+
private:
30+
struct CharacterAndCount {
31+
char character;
32+
int 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+
public:
9+
int firstUniqChar(string s) {
10+
queue<CharacterAndCount> characters;
11+
map<char, int> character_to_count;
12+
for (int i = 0; i < s.size(); ++i) {
13+
char c = s[i];
14+
++character_to_count[c];
15+
characters.push({c, i});
16+
while (character_to_count[characters.front().character] >= 2) {
17+
characters.pop();
18+
}
19+
}
20+
if (characters.empty()) {
21+
return -1;
22+
}
23+
return characters.front().index;
24+
}
25+
26+
private:
27+
struct CharacterAndCount {
28+
char character;
29+
int index;
30+
};
31+
};

0 commit comments

Comments
 (0)