diff --git a/387-first-unique-character-in-string/driver.cpp b/387-first-unique-character-in-string/driver.cpp new file mode 100644 index 0000000..ab0a185 --- /dev/null +++ b/387-first-unique-character-in-string/driver.cpp @@ -0,0 +1,10 @@ +#include "soln.hpp" + +int main() +{ + string s = "kaushiknarayanravishankar"; + int answer = 2; + Solution soln; + cout << "Found first unique character correctly? " << soln.test(s, answer) << endl; + return 0; +} \ No newline at end of file diff --git a/387-first-unique-character-in-string/soln.cpp b/387-first-unique-character-in-string/soln.cpp new file mode 100644 index 0000000..e6eaab2 --- /dev/null +++ b/387-first-unique-character-in-string/soln.cpp @@ -0,0 +1,26 @@ +#include "soln.hpp" + +int Solution::firstUniqChar(string s) +{ + map counts = map(); + + // get counts of all unique chars in s + for (int i = 0; i < s.length(); i++) + { + counts[s[i]]++; + } + + // go through string and get first char with count = 1 + for (int i = 0; i < s.length(); i++) + { + if (counts[s[i]] == 1) + { + return i; + } + } + return -1; +} + +bool Solution::test(string s, int answer) { + return firstUniqChar(s) == answer; +} \ No newline at end of file diff --git a/387-first-unique-character-in-string/soln.hpp b/387-first-unique-character-in-string/soln.hpp new file mode 100644 index 0000000..b129693 --- /dev/null +++ b/387-first-unique-character-in-string/soln.hpp @@ -0,0 +1,10 @@ +#include + +using namespace std; + +class Solution +{ +public: + int firstUniqChar(string s); + bool test(string s, int answer); +}; \ No newline at end of file