Design Compressed String Iterator
Description
null
Solution(javascript)
/**
* @param {string} compressedString
*/
const StringIterator = function (compressedString) {
this.str = compressedString.split(/[0-9]/g).join('')
this.counts = compressedString.split(/[a-zA-Z]/g)
.filter(x => x !== '')
.map(x => Number(x))
this.index = 0
}
/**
* @return {character}
*/
StringIterator.prototype.next = function () {
if (this.counts[this.index] === 0) {
this.index += 1
}
if (this.counts[this.index] > 0) {
this.counts[this.index] -= 1
return this.str[this.index]
}
return ' '
}
/**
* @return {boolean}
*/
StringIterator.prototype.hasNext = function () {
return this.counts[this.index] > 0 || this.counts[++this.index] > 0
}