Can anybody tell me how to implement a program to check a string contains all unique chars ?
Algorithm (without an additional data structure)Start the loop and then iterate through the characters of a string. Check the values of the characters that are next to each other. If the value does not match for all the pairs of characters in a string, then the string has all unique characters.
A unique string consists of characters that occur only once. To check for uniqueness, compare each character with the rest of the string. If a character is repeated, then the string is not unique.
Using Python's import numpy, the unique elements in the array are also obtained. In the first step convert the list to x=numpy. array(list) and then use numpy. unique(x) function to get the unique values from the list.
If you are talking about an ASCII string:
Create an int array [0-255], one for each character index, initialised to zero.
Loop through each character in the string and increment the respective array position for that character
If the array position already contains a 1, then that character has already been encountered. Result => Not unique.
If you reach the end of the string with no occurrence of (3), Result => the string is unique.
Sort the characters in the string using your algorithm of choice (e.g. the builtin qsort
function), then scan the string checking for consecutive repeating letters; if you get to the end without finding any, the string contains all unique characters.
An alternative may be using some structure that has one bucket for each character the string may contain, all initialized to zero; you scan the string, incrementing the value of the bucket corresponding to the current character. If you get to increment a bucket that already has a 1 inside it you are sure that your string contains duplicates.
This can work fine with char
s and an array (of size UCHAR_MAX+1
), but it quickly gets out of hand when you start to deal with wide characters. In such case you would need a hashtable or some other "serious" container.
The best algorithm depends on the length of the strings to examine, the size of each character, the speed of the sorting algorithm and the cost of allocating/using the structure to hold the character frequencies.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With