C language exercise question 51: Determine whether a character is unique

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

Algorithm idea: 1. Define an int type integer s. The binary digits of s are greater than 26. Use each binary digit of s to mark characters. 2. Traverse the string array and record the current character. The order in the word list is w, then mark the w-th bit of s as 1. If the w-th bit has been marked as 1, return false;

3. If no duplicate words are found at the end of the traversal, true will be returned.

• Mark the w-th bit: Add 1 to the w-th bit, which is equivalent to adding 2^(w-1) to the variable s. Here you can use the left shift operator in bit operations. Shifting a binary number to the left by one bit is equivalent to multiplying it by 2 once. Then 2^(w-1) can be expressed as 1<<(w -1) (1 and 2 are multiplied w-1 times).

• Determine whether the w-th bit has been marked: Use the & operator here, remember u=1<<(w-1). If s&u is 0, it means that the w-th bit has not been marked, otherwise the w-th bit has not been marked. Already marked. For example: 100100&100=100, means that the third digit of the previous number is marked, 100010&100=0, means that the third digit of the previous number is not marked.

bool isUnique(char* astr) {
	//定义变量⽤来标记
	int s = 0;
	int i = 0;
	while (astr[i]) {
		//在这⾥定义u直接表⽰为左移后的结果
        //astr[i]-'a'即为astr[i]在字⺟表中的顺序-1,即上⾯所说的w-1
		int u = 1 << (int)(astr[i] - 'a');
		if ((s & u) == 0) {
			s += u;
		}
		else
			return false;
	}
	return true;
}

Guess you like

Origin blog.csdn.net/2301_77479435/article/details/132812702