Several methods to determine whether all characters in a string are the same

Implement an algorithm to determine whether all characters of a string s are different.

Example 1:

Input: s = "leetcode"
Output: false
Example 2:

Input: s = "abc"
Output: true

The easiest thing to think about for this problem is to sort first, and then use a loop to determine whether the previous and previous elements are equal. The time complexity is at least O(nlogn);
you can also use set deduplication or unordered_map key-value pairs to achieve linear complexity. However, additional space is required; a small point, if the value of the key-value pair is int, the initialization default is 0, and there is no need to assign a value;
the most difficult thing to think of is bit operation, setting an int 0 as a standard element. Each time, the difference between a character and a is bitwise ORed with 0. At this time, if a bit is 1, it means that the letter exists. Then perform a bitwise AND operation. If it occurs twice, the result of the bitwise AND must be 1. You can return false.

class Solution {
public:
    bool isUnique(string astr) {
        // int n=astr.length();
        // if(n==0)
        //     return true;
        // unordered_set<char> tmp;
        // for(int i=0;i<n;i++)
        // {
        //     tmp.emplace(astr[i]);
        // } 
        // int m=tmp.size();
        // if(m==n)
        //     return true;
        // else
        //     return false;

    
    //
        // unordered_map<char,int> hash;//value默认为0
        // int n=astr.length();
        // int flag=1;
        // if(n==0)
        //     return true;
        // for(int i=0;i<n;i++)
        // {
        //     hash[astr[i]]+=1;
        // }
        // for(auto iter=hash.begin();iter!=hash.end();iter++)
        // {
        //     if(iter->second>1)
        //     {
        //         flag=0;
        //         break;
        //     }
        // }
        // if(flag==1)
        //     return true;
        // else
        //     return false;
        ///
        int cnn=0;
        int n=astr.size();
        if(n==0)
            return true;
        for(int i=0;i<n;i++)
        {
            if(cnn&(1<<(astr[i]-'a')))
                return false;
            cnn=cnn|(1<<(astr[i]-'a'));
        }
        return true;
    }
};

But please note that int only has 32 bits, so it can only judge 32 types of characters. The test cases for this question are all lowercase letters, so it can pass. If there are other special characters, it is not necessarily the case. It must be at least 128 bits, so it is clever. method is not suitable for every situation.

Guess you like

Origin blog.csdn.net/weixin_53344209/article/details/126473230#comments_27407726