316 Remove Duplicate Letters
Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.
Example:
Given "bcabc"
Return "abc"
Given "cbacdcbc"
Return "acdb"// attempt: 1 -> does not return in smallest lexical-graphical order
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
void print1d(vector<int> &nums) { for (auto i : nums) cout << i << ' '; cout << endl; }
void printMap(map<char, int> &myMap) {
for (auto i : myMap) {
cout << i.first << " => " << i.second << endl;
}
}
map<char, int> mapAlpha() {
map<char, int> alpha;
for (int i = 0; i < 26; i++) {
alpha.insert({ static_cast<char>('a' + i), 0 });
}
return alpha;
}
string removeDuplicateLetters(string s) {
map<char, int> alphaCount = mapAlpha();
//printMap(alphaCount);
for (int i = 0; i < s.size(); ++i) {
// duplicate exists
if (alphaCount.find(s.at(i))->second != 0) {
s.erase(s.begin() + i);
i--;
}
// unique letter
else {
alphaCount.find(s.at(i))->second = 1;
}
}
return s;
}
int main()
{
string s = "aaacomn";
string result = removeDuplicateLetters(s);
cout << result << endl;
}// attempt2:
Brainstorming:
For every duplicate, measure its displacement distance to every other non-duplicate element. Then add this elements together. So for every duplicate there will be a number associated with it. Finally, all duplicate positions will be erased from the string, except for the position with the minimum distance.
Really slow, and I am sure there is a better solution - but it's my current intuition.
Retrospect:
I will likely rewriting this entire program again from scratch. There are too many redudancies, and very difficult to read implementation. Functions are not reproducable, and I am pretty sure there is an entirely different, but better algorithm that is both simplier and more efficient. This was good practice, I suppose.
// attempt3:
Last updated
Was this helpful?