-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
}; |