Bitshift操作和位掩码未检测到重复字符

问题描述 投票:0回答:1

我一直在尝试编写一个程序,使用位掩码检查小写输入中的重复字母。但是,无论是否存在重复的字母,程序都会返回true。代码如下:

#include <iostream>
#include <cctype>
#include <cstring>

using namespace std;

bool all_unique_letters(const string &s) {
    int bitset;

    for(char const &c : s)
    {
        unsigned char set = 1 << (c - 'a');

        if(set & bitset)
            return false;

        bitset |= set;
    }

    return true;
}

int main(int argc, char * const argv[]) {
    // TODO: reads and parses command line arguments.
    // Calls other functions to produce correct output.
    if(all_unique_letters(argv[1]))
        cout << "All letters are unique!" << endl;
    else
        cout << "Duplicate letters found." << endl;
}
c++ bit-shift bitmask
1个回答
0
投票

我看到两个问题。首先,您的bitset变量未初始化。其次,set变量的类型为unsigned char 8位类型。对于小写字母,您至少需要26位才能对bitset进行测试。解决两个问题后,您的代码似乎可以正常工作。

bool all_unique_letters(const string &s) {
    int bitset = 0; // fixed

    for(char const &c : s)
    {
        int set = 1 << (c - 'a'); // fixed

        if(set & bitset)
            return false;

        bitset |= set;
    }
    return true;
}
© www.soinside.com 2019 - 2024. All rights reserved.