检查字符串是否包含字母表中的所有字母

Viv*_*vek 4 java algorithm logic

检查给定字符串中所有字母的最佳逻辑是什么.

如果提供的字符串中有26个字母都可用,我想检查并执行操作.例如.用五十个酒壶包装我的盒子.

  1. 使用Hash会有用吗?
  2. 或者使用位图?或任何其他方式?

顺便说一句,我的代码将是Java.

st0*_*0le 6

使用BitMap,我假设你的意思是不区分大小写.

更新:托马斯的解决方案比以下更有效.:)使用那个.

    //
    String test  = "abcdefeghjiklmnopqrstuvwxyz";

    BitSet alpha = new BitSet(26);
    for(char ch : test.toUpperCase().toCharArray())
        if(Character.isLetter(ch))
            alpha.set(ch - 65);

    System.out.println(alpha.cardinality() == 26);
Run Code Online (Sandbox Code Playgroud)


Tho*_*ler 5

尚未完全优化:

public static void main(String... a) {
    String s = "Pack my box with five dozen liquor jugs.";
    int i=0;
    for(char c : s.toCharArray()) {
        int x = Character.toUpperCase(c);
        if (x >= 'A' && x <= 'Z') {
            i |= 1 << (x - 'A');
        }
    }
    if (i == (i | ((1 << (1 + 'Z' - 'A')) - 1))) {
        System.out.println("ok");
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 实际上,不需要(i | ...),你也可以使用if(i ==(1 <<(1 +'Z' - 'A')) - 1) - 或Integer.bitCount(i) == 26. (4认同)