Java 在不使用其他数据结构的情况下,使用位操作验证ascii字符串是否包含唯一字符

Java 在不使用其他数据结构的情况下,使用位操作验证ascii字符串是否包含唯一字符,java,algorithm,bit-manipulation,Java,Algorithm,Bit Manipulation,我试图解决这个问题,但当输入字符串中包含相同字母表的大小写版本时,我的程序失败,例如:-Test,Abca // Assuming Input to be an ASCII String i.e a total of 128 unique characters, which map to the numbers 0–127. public class Q1_1 { public static void main(String[] args) { long firstHa

我试图解决这个问题,但当输入字符串中包含相同字母表的大小写版本时,我的程序失败,例如:-Test,Abca

// Assuming Input to be an ASCII String i.e a total of 128 unique characters, which map to the numbers 0–127.

public class Q1_1 {
    public static void main(String[] args) {
        long firstHalf = 0; // 0 - 63
        long secondHalf = 0; // 64 - 127
        Scanner sc = new Scanner(System.in);
        String x = sc.nextLine();
        for(int i = 0; i < x.length(); i++) {
            byte b = (byte) x.charAt(i);
            System.out.println((char) b + " - " + b);
            if(b < 63) { // search firstHalf
                System.out.println("First Half");
                long mask = 1 << b;
                if((firstHalf & mask) == 0) { // unique character is encountered
                    firstHalf |= mask;
                } else {
                    System.out.println("String contains Duplicate Character");
                    return;
                }
            } else if(b > 63 && b < 128) {
                System.out.println("Second Half");
                long mask = 1 << (b - 64);
                if((secondHalf & mask) == 0) {  // unique character is encountered
                    secondHalf |= mask;
                } else {
                    System.out.println("String contains Duplicate Character");
                    return;
                }
            }
        }
        System.out.println("ASCII String contains only unique character");
    }
}
//假设输入为ASCII字符串,即总共128个唯一字符,映射到数字0–127。
公开课Q1_1{
公共静态void main(字符串[]args){
长的前半部分=0;//0-63
long secondHalf=0;//64-127
扫描仪sc=新的扫描仪(System.in);
字符串x=sc.nextLine();
对于(int i=0;i长掩码=1这是因为位移位:

(1 << (b - 64))

(1击败我:)它只是将掩码中的任何内容归零
b>=32
(b-64)>=32
否?@madpysicast它屏蔽了数字的前5位。我不知道。直到。谢谢:)
(1L << (b - 64))