Tcdian / keep

今天不想做,所以才去做。
MIT License
5 stars 1 forks source link

1286. Iterator for Combination #297

Open Tcdian opened 3 years ago

Tcdian commented 3 years ago

1286. Iterator for Combination

请你设计一个迭代器类,包括以下内容:

Example

CombinationIterator iterator = new CombinationIterator("abc", 2); // creates the iterator.

iterator.next(); // returns "ab"
iterator.hasNext(); // returns true
iterator.next(); // returns "ac"
iterator.hasNext(); // returns true
iterator.next(); // returns "bc"
iterator.hasNext(); // returns false

Note

Tcdian commented 3 years ago

Solution

/**
 * @param {string} characters
 * @param {number} combinationLength
 */
var CombinationIterator = function(characters, combinationLength) {
    this.characters = characters;
    this.combinationLength = combinationLength;
    this.nextValue = Array.from(new Array(combinationLength), (_, index) => index);
    this.done = false;
};

/**
 * @return {string}
 */
CombinationIterator.prototype.next = function() {
    const result = this.nextValue.map((index) => this.characters[index]).join('');
    this.done = true;
    for (let i = this.nextValue.length - 1; i >= 0; i--) {
        if (this.nextValue[i] < this.characters.length - 1 - (this.nextValue.length - 1 - i)) {
            this.nextValue[i] += 1;
            for (let j = i + 1; j < this.nextValue.length; j++) {
                this.nextValue[j] = this.nextValue[j - 1] + 1;
            }
            this.done = false;
            break;
        }
    }
    return result;
};

/**
 * @return {boolean}
 */
CombinationIterator.prototype.hasNext = function() {
    return !this.done;
};

/** 
 * Your CombinationIterator object will be instantiated and called as such:
 * var obj = new CombinationIterator(characters, combinationLength)
 * var param_1 = obj.next()
 * var param_2 = obj.hasNext()
 */
class CombinationIterator {
    nextValue: number[];
    done: boolean;
    constructor(private characters: string, private combinationLength: number) {
        this.nextValue = Array.from(new Array(combinationLength), (_, index) => index);
        this.done = false;
    }

    next(): string {
        const result = this.nextValue.map((index) => this.characters[index]).join('');
        this.done = true;
        for (let i = this.nextValue.length - 1; i >= 0; i--) {
            if (this.nextValue[i] < this.characters.length - 1 - (this.nextValue.length - 1 - i)) {
                this.nextValue[i] += 1;
                for (let j = i + 1; j < this.nextValue.length; j++) {
                    this.nextValue[j] = this.nextValue[j - 1] + 1;
                }
                this.done = false;
                break;
            }
        }
        return result;
    }

    hasNext(): boolean {
        return !this.done;
    }
}

/**
 * Your CombinationIterator object will be instantiated and called as such:
 * var obj = new CombinationIterator(characters, combinationLength)
 * var param_1 = obj.next()
 * var param_2 = obj.hasNext()
 */