Created
November 30, 2016 04:36
-
-
Save cwcai633/c7beb5c5bf4b69a53cfa69884e4d3518 to your computer and use it in GitHub Desktop.
Find a subsequence with length k and is smallest in lexicographical order
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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