-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
1286. Iterator for Combination #297
Labels
Comments
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()
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
1286. Iterator for Combination
请你设计一个迭代器类,包括以下内容:
有序且字符唯一
的字符串 characters(该字符串只包含小写英文字母)和一个数- 字combinationLength
。字典序
返回长度为combinationLength
的下一个字母组合。combinationLength
的下一个字母组合时,才返回True
;否则,返回False
。Example
Note
1 <= combinationLength <= characters.length <= 15
10^4
次函数调用。next
时都存在下一个字母组合。The text was updated successfully, but these errors were encountered: