class CombinationIterator {
public:
string str;
long long status;
long long nextstatus;
int N; // 整体长度
int L; // 组合长度
bool Dohasnext;
bool lastflag;
bool firsttime;
CombinationIterator(string characters, int combinationLength) {
N = characters.length();
L = combinationLength;
str = characters;
status = 0;
Dohasnext = false;
lastflag = true;
firsttime = true;
for(int i=0;i<L;i++){
status <<= 1;
status ++;
}
for(int i=L;i<N;i++){
status <<=1;
}
nextstatus = status;
}
string next() {
if(hasNext()){
Dohasnext = false;
string ans = "";
for(int i=0;i<N;i++){
if( ( nextstatus & (1<< (N-i-1) ) ) != 0){
ans += str[i];
}
}
return ans;
}
return "";
}
bool hasNext() {
if(N<L){
lastflag = false;
return false;
}
if(Dohasnext) return lastflag;
Dohasnext = true;
if(firsttime){
firsttime = false;
lastflag = true;
return true;
}
int flag = 0;
for(int i=0;i<N;i++){
if( (status & (1<<i)) != 0){
flag ++; // 存在1的个数
}else{
if(flag){
if(flag >= L){
lastflag = false;
return false;
}
// 存在1,零最左边1右移,其他顺后
for(int j=i+1;j<N;j++){
// 第一个1
if( (status & (1<<j)) != 0){
status &= (status+1);
status ^= (1<<j);
for(int k=0;k<=flag;k++){
status ^= (1<<(j-1-k));
}
nextstatus = status;
lastflag = true;
return true;
}
}
}else{
// 全是零,最左边1右移
for(int j=i+1;j<N;j++){
if( (status & (1<<j)) != 0){
status ^= (1<<j);
status ^= (1<<(j-1));
nextstatus = status;
lastflag = true;
return true;
}
}
}
}
}
lastflag = false;
return false;
}
};
/**
* Your CombinationIterator object will be instantiated and called as such:
* CombinationIterator* obj = new CombinationIterator(characters, combinationLength);
* string param_1 = obj->next();
* bool param_2 = obj->hasNext();
*/
No.156 - LeetCode? - Iterator for Combination
最新推荐文章于 2024-10-14 17:32:24 发布