Easiest way of checking if a string consists of unique characters?

前端 未结 12 1813
慢半拍i
慢半拍i 2021-01-04 23:34

I need to check in Java if a word consists of unique letters (case insensitive). As straight solution is boring, I came up with:

  1. For every char in a string che
12条回答
  •  执念已碎
    2021-01-05 00:34

    What about using an int to store the bits corresponding to the index of the letter of the alpabhet? or maybe a long to be able to reach 64 distinct symbols.

    long mask;
    // already lower case
    string = string.toLowerCase();
    for (int i = 0; i < string.length(); ++i)
    {
      int index = 1 << string.charAt(i) - 'a';
      if (mask & index == index)
        return false;
    
      mask |= index;
    }
    return true;
    

    This should be < O(n) on average case, O(n) on worst. But I'm not sure how much performant bitwise operations are in Java..

提交回复
热议问题