-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathGFG_NonRepeatingChar.cpp
109 lines (80 loc) · 1.99 KB
/
GFG_NonRepeatingChar.cpp
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/*
https://practice.geeksforgeeks.org/problems/non-repeating-character-1587115620/1/#
Non-Repeating Character
https://leetcode.com/problems/first-unique-character-in-a-string/
387. First Unique Character in a String
*/
/***************** LEETCODE **************************/
class Solution {
public:
int firstUniqChar(string s) {
vector<int> hash(26,-1);
for(int i=0; i<s.size(); i++)
{
int ind = s[i]-'a';
if(hash[ind] == -1)
hash[ind] = i;
else
hash[ind] = -2;
}
int res = INT_MAX;
for(int i=0; i<hash.size(); i++)
{
if(hash[i]>=0)
{
res = min(res, hash[i]);
}
}
if(res != INT_MAX) return res;
return -1;
}//end
};
/***************** GFG **************************/
// { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
public:
//Function to find the first non-repeating character in a string.
char nonrepeatingCharacter(string S)
{
//Your code here
vector<int> hash(26,-1);
for(int i=0; i<S.size(); i++)
{
int ind = S[i]-'a';
if(hash[ind] == -1) // first time occurance
hash[ind] = i;
else
hash[ind] = -2; //more than once
}
int res = INT_MAX;
for(int i=0; i<hash.size(); i++)
{
if(hash[i]>=0)
res = min(res, hash[i]);
}
if(res != INT_MAX) return (S[res]);
return '$';
}//end
};
// { Driver Code Starts.
int main() {
int T;
cin >> T;
while(T--)
{
string S;
cin >> S;
Solution obj;
char ans = obj.nonrepeatingCharacter(S);
if(ans != '$')
cout << ans;
else cout << "-1";
cout << endl;
}
return 0;
}
// } Driver Code Ends