Tips and Tricks for Strings
Common operations
Sort a string alphabetically
- Python
def sort_string(a)
return ''.join(sorted(a))
Miscellaneous
Count the characters in a string of unique characters
A neat trick to count the characters in a string of unique characters is to use a 26-bit bitmask to indicate which lower case Latin characters are inside the string.
- Python
mask = 0
for c in word:
mask |= (1 << (ord(c) - ord('a')))
To determine if two strings have common characters, perform &
on the two bitmasks. If the result is non-zero (i.e., mask_a & mask_b > 0
) then the two strings have common characters.