Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Created June 11, 2017 03:45
Show Gist options
  • Save dgodfrey206/28784256046c2ee1aae2ba4ddc1dbb1e to your computer and use it in GitHub Desktop.
Save dgodfrey206/28784256046c2ee1aae2ba4ddc1dbb1e to your computer and use it in GitHub Desktop.
class StringIterator {
public:
StringIterator(string compressedString) : compressedString(compressedString) {
size_t i = 0;
while (i < compressedString.size()) {
freqTable.push_back(make_pair(compressedString[i++], 0));
int freq = 0;
while (i < compressedString.size() && isdigit(compressedString[i])) {
freq = (freq * 10) + (compressedString[i] - '0');
i++;
}
freqTable.back().second += freq;
}
}
char next() {
if (!hasNext()) {
return ' ';
}
char c = freqTable[idx].first;
freqTable[idx].second--;
if (freqTable[idx].second == 0) {
idx++;
}
return c;
}
bool hasNext() {
return idx < freqTable.size();
}
size_t idx = 0;
string compressedString;
vector<pair<char, int>> freqTable;
};
/**
* Your StringIterator object will be instantiated and called as such:
* StringIterator obj = new StringIterator(compressedString);
* char param_1 = obj.next();
* bool param_2 = obj.hasNext();
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment