-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfirstUniqueCharacterInAString.cpp
More file actions
61 lines (51 loc) · 1.06 KB
/
firstUniqueCharacterInAString.cpp
File metadata and controls
61 lines (51 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
#include <unordered_map>
#include <string>
// https://leetcode.com/problems/first-unique-character-in-a-string/
class Solution
{
public:
int firstUniqChar(std::string s)
{
int length = s.length();
int resIndex = -1;
std::unordered_map<std::string, int> tempMap;
for (int i = 0; i < length; i += 1)
{
char curChar = s[i];
std::string curStr;
curStr.push_back(curChar);
if (tempMap.count(curStr) == 0)
{
tempMap[curStr] = 1;
}
else
{
tempMap[curStr] += 1;
}
}
bool isFound = false;
int j = 0;
while (!isFound && j < length)
{
char curChar = s[j];
std::string curStr;
curStr.push_back(curChar);
if (tempMap[curStr] == 1)
{
isFound = true;
resIndex = j;
}
j += 1;
}
return resIndex;
}
};
int main()
{
Solution SolutionInstance;
std::string s = "leetcode";
int result = SolutionInstance.firstUniqChar(s);
std::cout << "result is " << result << std::endl;
return 0;
}