Playing with the strings.
Posted: 22 Feb, 2021
Difficulty: Easy
Kevin loves playing with the strings only when they have unique characters. Once his father gave him a string that contains various characters. You have to find out whether Kevin will play with it or not.
Note:
The string may contain English alphabets, numbers, and special characters.
Input Format:
The first line contains a single integer ‘T’ representing the number of test cases.
The first line of each test case will contain a string ‘S’.
Output Format:
For each test case, return 'true' if Kevin will play with the given string. Otherwise, return 'false'.
Print the output for each test case in a separate line.
Note:
You don’t need to print anything, It has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 1000
1 <= |S| <= 100
Where '|S|' is the length of the given string.
Time limit: 1 sec
Approach 1
The basic idea is to iterate through all the array elements and check whether each character uniquely exists in the string or not.
The steps are as follows:
- Iterate through the string ‘S’ (say, iterator = ‘i’).
- Iterate through the string ‘S’ again but from (‘i’ + 1) to the string’s end.
- Check If anywhere found the same characters then return false.
- Iterate through the string ‘S’ again but from (‘i’ + 1) to the string’s end.
- Return true if there exist unique characters.
Approach 2
The basic idea of this approach is to sort the characters of the string ‘S’ in increasing order and check if there exist any duplicates, then return false. Otherwise, return true.
The steps are as follows:
- Sort the given string.
- Iterate through the string (say, iterator = ‘i’)
- If at any point the character at ‘i’ is the same as the character at (‘i’ - 1) then return false.
- Iterate through the string (say, iterator = ‘i’)
- Return true if there is not any single duplicate character present in the given string.
Approach 3
The basic idea of this approach is to insert all the characters of the given string into a HashSet and then check if the size of HashSet is the same as the given string or not. If it is the same, which means there are no duplicates in the string.
The steps are as follows:
- Create a HashSet to store the characters.
- Iterate through the string ‘S’.
- Insert each character into the HashSet.
- If, the size of HashSet is the same as the given string then return true.
- Otherwise, return false.