Skip to content

Commit

Permalink
Create 1286.Iterator-for-Combination.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
wisdompeak authored Feb 8, 2020
1 parent c89a411 commit 945e2f2
Showing 1 changed file with 42 additions and 0 deletions.
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;
}
};

0 comments on commit 945e2f2

Please sign in to comment.