Given an Iterator<String>, produce an iterator that returns items of type Pair<String, Integer> that return the String retrieved from the original iterator, and the number of times in a row the string appears.
class WordAndCount {
public String word;
public int count;
}
class CountingIterator implements Iterator<WordAndCount> {
public CountingIterator(Iterator<String> words) {
}
public WordAndCount next() {
}
public boolean hasNext() {
}
}Example:
CountingIterator it = new CountingIterator([foo, foo, foo, bar, foo, bar, bar]);
it.hasNext(); // true
it.next(); // <foo, 3>
it.next(); // <bar, 1>
it.next(); // <foo, 1>
it.next(); // <bar, 2>
it.hasNext(); // false
it.next(); // errorJava solution using PeekingIterator: https://leetcode.com/playground/DL3y9jQs
Follow-up:
Input is List<Iterator<String>> iterators.
Example:
CountingIterator it = new CountingIterator([foo, foo, foo, bar, foo], [foo, bar], [bar, foo]]);
it.hasNext(); // true
it.next(); // <foo, 3>
it.next(); // <bar, 1>
it.next(); // <foo, 2>
it.next(); // <bar, 2>
it.next(); // <foo, 1>
it.hasNext(); // false
it.next(); // error