Determine if a string has all unique characters using a bit vector in C++

preview_player
Показать описание
Determine if a string has all unique characters using a bit vector and bitshifting in C++
Рекомендации по теме
Комментарии
Автор

It's a little inefficient...

Three things should be changed:
1.: loop from the end of the string to 0. The for loop will read the length of the string each time the loop repeats. If you reverse, the loop variable has to be compared to 0 each time.
84 for (i = str.length () - 1; i >= 0; --i)
2.: You are doing the bitshift twice, using the distance in a 'val'. You can store the shifted 1 in 'val' and use it in both places
87 int val = 1 << (str[i] - 'a');
94 if ((checker & val) > 0)
101 checker |= val;
3.: Checking, if the bit is set by asking, if the result of the bitwise & is greater than zero requires a subtraction in the assembler code. The result of that subtraction is stored in the zero-flag and the carry-flag of the CPU. Those are then tested to see, if the result is > 0.
The bitwise & will also set the zero-flag of the CPU, which allows to check the result immediately.
94 if (checker & val)

You might think, these changes make your code only nanoseconds faster, nowadays with CPUs, that run at gigahertz speeds, but imagine, one of your students will develop a gadget, that is sold a billion times... The amount of excess CO2, produced by those things will literally be breathtaking.

michaelbuchholz