-
Notifications
You must be signed in to change notification settings - Fork 0
/
removeDuplicateLetter.cpp
67 lines (52 loc) · 1.42 KB
/
removeDuplicateLetter.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
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function that finds lexicographically
// smallest string after removing the
// duplicates from the given string
string removeDuplicateLetters(string s)
{
// Stores the frequency of characters
int cnt[26] = { 0 };
// Mark visited characters
int vis[26] = { 0 };
int n = s.size();
// Stores count of each character
for (int i = 0; i < n; i++)
cnt[s[i] - 'a']++;
// Stores the resultant string
string res = "";
for (int i = 0; i < n; i++) {
// Decrease the count of
// current character
cnt[s[i] - 'a']--;
// If character is not already
// in answer
if (!vis[s[i] - 'a']) {
// Last character > S[i]
// and its count > 0
while (res.size() > 0
&& res.back() > s[i]
&& cnt[res.back() - 'a'] > 0) {
// Mark letter unvisited
vis[res.back() - 'a'] = 0;
res.pop_back();
}
// Add s[i] in res and
// mark it visited
res += s[i];
vis[s[i] - 'a'] = 1;
}
}
// Return the resultant string
return res;
}
// Driver Code
int main()
{
// Given string S
string S = "acbc";
// Function Call
cout << removeDuplicateLetters(S);
return 0;
}