Created
January 7, 2018 19:09
-
-
Save jianminchen/3e260a6b076dd0cdc292000654e4a831 to your computer and use it in GitHub Desktop.
Smallest substring of all characters - the solution passes all test cases, but time complexity should be reviewed.
This file contains 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 <vector> | |
#include <string> | |
#include <unordered_set> | |
#include <unordered_map> | |
using namespace std; | |
string getShortestUniqueSubstring( const vector<char>& arr, const string &str ) | |
{ | |
// your code goes here | |
unordered_set<char> set; | |
for (int i = 0; i < arr.size(); i++) { | |
set.emplace(arr[i]); | |
} | |
unordered_map<char, int> map; | |
int head = 0; | |
int minLength = INT_MAX; | |
int runner = 0; | |
string result; | |
while (runner < str.size() && head <= runner) { | |
char currentChar = str[runner]; | |
if (set.count(currentChar) != 0) { | |
map[currentChar]++; | |
} | |
if (map.size() == set.size()) { | |
int distance = runner - head + 1; | |
if (distance < minLength) { | |
minLength = distance; | |
result = str.substr(head, distance); | |
} | |
head++; | |
runner = head - 1; // ? | |
map.clear(); | |
} | |
runner++; | |
} | |
if (minLength == INT_MAX) | |
return ""; | |
return result; | |
} | |
int main() { | |
return 0; | |
} | |
/* | |
xxxyz -> xyz | |
xyyzyzyx | |
xyyz -> extra y "xyyz" -> minSubtring | |
xxxyyz -> extra 2 -> dictionary<'x', -2>, xx -> xyyz -> "xyyz" | |
O(n) -> | |
axyz -> "axyz" -> 'a' -> "xyz" | |
hard level -> 30 minutes | |
^ | |
[x, y, z] | |
time complexity | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment