Skip to content

Commit

Permalink
add queue and map solve
Browse files Browse the repository at this point in the history
  • Loading branch information
colorbox committed Nov 30, 2024
1 parent 48f2749 commit 3abf803
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
34 changes: 34 additions & 0 deletions 387/step2_2_suggested.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
https://github.com/colorbox/leetcode/pull/29#discussion_r1861430039
を見てそれを参考に自分で書いた解法、比較用
*/
class Solution {
private:
struct CharacterAndCount {
char character;
int index;
};

public:
int firstUniqChar(string s) {
queue<CharacterAndCount> queue;
map<char, int> character_to_count;
for (int i = 0; i < s.size(); i++) {
char c = s[i];
character_to_count[c]++;
queue.push({c, i});
while (true) {
char front_character = queue.front().character;
if (character_to_count[front_character] > 1) {
queue.pop();
} else {
break;
}
}
}
if (queue.empty()) {
return -1;
}
return queue.front().index;
}
};
31 changes: 31 additions & 0 deletions 387/step2_2_suggested_fixed.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
step2_2_suggested.cpp
https://github.com/colorbox/leetcode/pull/29#discussion_r1861430039
の書き方に沿って修正したコード、参照用
*/
class Solution {
private:
struct CharacterAndCount {
char character;
int index;
};

public:
int firstUniqChar(string s) {
queue<CharacterAndCount> characters;
map<char, int> character_to_count;
for (int i = 0; i < s.size(); ++i) {
char c = s[i];
++character_to_count[c];
characters.push({c, i});
while (character_to_count[characters.front().character] >= 2) {
characters.pop();
}
}
if (characters.empty()) {
return -1;
}
return characters.front().index;
}
};

0 comments on commit 3abf803

Please sign in to comment.