Be the first user to complete this post
|
Add to List |
248. Remove Duplicates from a string | 4 Approaches
Objective: Given a string, write an algorithm to remove the duplicate characters in that string.
Example:
Input: tutorialhorizon Output: tuorialhzn
Approaches:
There are multiple approaches to solve this problem-
- Use Sorting – (Will change the order of the characters)
- Use Hash Set - (Will change the order of the characters).
- Use Linked HashMap - (Will retain the order of the characters).
- Use Buffer Array - (Will retain the order of the characters).
Let’s discuss all the approaches
Sorting:
- Convert the string to character array. S
- Sort the array, this will bring all the identical characters together.
- Iterate through character array and remove the duplicate characters.
- This approach will change the order of characters.
Output: ahilnortuz
Hash Set:
- Convert the string to character array.
- Store all the characters in the Set.
- Set will store only one instance of each character
- Iterate through Set and print the characters.
- This approach will change the order of characters.
Output: artuhizlno
Linked Hash Set:
- Convert the string to character array.
- Store all the characters in the Linked Hash Set.
- Set will store only one instance of each character
- Iterate through Set and print the characters.
- This approach will retain the order of characters.
Output: tuorialhzn
Buffer Array:
- Convert the string to character array.
- Create the boolean array of 256,( for all 0 – 255 ASCII characters)
- Iterate through character array from step one and set the Boolean array index ( index = ascii value of the character). Ignore if that index is already true.
- Create a separate array based on the index set as true in Boolean array.
- This approach will retain the order of characters.
Output: tuorialhzn