Java Program To Remove Duplicates From A Given String
Write a java program for a given string S, the task is to remove all the duplicates in the given string.
Below are the different methods to remove duplicates in a string.
Note: The order of remaining characters in the output should be the same as in the original string.
Example:
Input: Str = geeksforgeeks
Output: geksfor
Explanation: After removing duplicate characters such as e, k, g, s, we have string as “geksfor”.
Input: Str = HappyNewYear
Output: HapyNewYr
Explanation: After removing duplicate characters such as p, e, a, we have string as “HapyNewYr”.
Naive Approach:
Iterate through the string and for each character check if that particular character has occurred before it in the string. If not, add the character to the result, otherwise the character is not added to result.
Below is the implementation of above approach:
Java
import java.util.*;
class GFG {
static String removeDuplicate( char str[], int n)
{
int index = 0 ;
for ( int i = 0 ; i < n; i++) {
int j;
for (j = 0 ; j < i; j++) {
if (str[i] == str[j]) {
break ;
}
}
if (j == i) {
str[index++] = str[i];
}
}
return String.valueOf(Arrays.copyOf(str, index));
}
public static void main(String[] args)
{
char str[] = "geeksforgeeks" .toCharArray();
int n = str.length;
System.out.println(removeDuplicate(str, n));
}
}
|
Output:
geksfor
Time Complexity : O(n * n)
Auxiliary Space : O(1) , Keeps order of elements the same as input.
Remove duplicates from a given string using Hashing
Iterating through the given string and use a map to efficiently track of encountered characters. If a character is encountered for the first time, it’s added to the result string, Otherwise, it’s skipped. This ensures the output string contains only unique characters in the same order as the input string.
Below is the implementation of above approach:
Java
import java.util.*;
class GFG {
static char [] removeDuplicates( char [] s, int n)
{
Map<Character, Integer> exists = new HashMap<>();
String st = "" ;
for ( int i = 0 ; i < n; i++) {
if (!exists.containsKey(s[i])) {
st += s[i];
exists.put(s[i], 1 );
}
}
return st.toCharArray();
}
public static void main(String[] args)
{
char s[] = "geeksforgeeks" .toCharArray();
int n = s.length;
System.out.print(removeDuplicates(s, n));
}
}
|
Output:
geksfor
Time Complexity: O(n)
Space complexity: O(n)
Please refer complete article on Remove duplicates from a given string for more details!
Last Updated :
13 Oct, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...