Skip to content

Instantly share code, notes, and snippets.

@cwcai633
Created November 30, 2016 04:36
Show Gist options
  • Select an option

  • Save cwcai633/c7beb5c5bf4b69a53cfa69884e4d3518 to your computer and use it in GitHub Desktop.

Select an option

Save cwcai633/c7beb5c5bf4b69a53cfa69884e4d3518 to your computer and use it in GitHub Desktop.
Find a subsequence with length k and is smallest in lexicographical order
#include <iostream>
#include <string>
using namespace std;
string findMin(string s, int k) {
string res = "";
int len = s.size();
for (int i = 0; i < len; i++) {
while (!res.empty() and res.back() > s[i] and len - i + res.size() > k) {
res.pop_back();
}
if (res.size() < k) {
res = res + s[i];
}
}
while (res.size() > k) {
res.pop_back();
}
return res;
}
int main() {
string s1 = "pineapple";
string s2 = "zyxwvuabc";
cout << findMin(s1, 3) << endl;
cout << findMin(s2, 6) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment