forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 1286.Iterator-for-Combination.cpp
- Loading branch information
1 parent
c89a411
commit 945e2f2
Showing
1 changed file
with
42 additions
and
0 deletions.
There are no files selected for viewing
42 changes: 42 additions & 0 deletions
42
Others/1286.Iterator-for-Combination/1286.Iterator-for-Combination.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
class CombinationIterator { | ||
string cur; | ||
string end; | ||
bool flag; | ||
string characters; | ||
int combinationLength; | ||
|
||
public: | ||
CombinationIterator(string characters, int combinationLength) | ||
{ | ||
cur = characters.substr(0,combinationLength); | ||
end = characters.substr(characters.size()-combinationLength); | ||
flag = 1; | ||
this->characters = characters; | ||
this->combinationLength = combinationLength; | ||
} | ||
|
||
string next() | ||
{ | ||
if (flag) | ||
{ | ||
flag = 0; | ||
return cur; | ||
} | ||
|
||
int i = cur.size()-1; | ||
while (i>=0 && cur[i]==characters[i+characters.size()-combinationLength]) | ||
i--; | ||
int j = 0; | ||
while (cur[i]!=characters[j]) | ||
j++; | ||
for (int k=i; k<cur.size(); k++) | ||
cur[k] = characters[j+1 + k-i]; // cur[i] = characters[j+1] | ||
|
||
return cur; | ||
} | ||
|
||
bool hasNext() | ||
{ | ||
return cur!=end; | ||
} | ||
}; |