day 6: 387-first-unique-character-in-string

This commit is contained in:
Kaushik Narayan R 2023-10-01 15:01:45 -07:00
parent 44d990d037
commit 3f9b5b69e5
3 changed files with 46 additions and 0 deletions

View File

@ -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;
}

View File

@ -0,0 +1,26 @@
#include "soln.hpp"
int Solution::firstUniqChar(string s)
{
map<char, int> counts = map<char, int>();
// 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;
}

View File

@ -0,0 +1,10 @@
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int firstUniqChar(string s);
bool test(string s, int answer);
};