Skip to content

Commit

Permalink
feat: Add method RemoveDuplicatesCharacters from string
Browse files Browse the repository at this point in the history
  • Loading branch information
Vishwajeet-29-pro committed Dec 6, 2024
1 parent 9a4d9bc commit d291beb
Showing 1 changed file with 45 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package org.practice.dsa.strings;

import java.util.HashSet;
import java.util.Set;

public class RemoveDuplicatesCharacters {
public static void main(String[] args) {
System.out.println(removeDuplicates("Vishwajeet"));
System.out.println(removeDuplicatesForLoop("principle"));
}

public static String removeDuplicates(String str) {
Set<Character> set = new HashSet<>();
StringBuilder builder = new StringBuilder();

for (char ch: str.toCharArray()) {
if (set.add(ch)) {
builder.append(ch);
}
}
return builder.toString();
}

// using for loops
public static String removeDuplicatesForLoop(String str) {
StringBuilder stringBuilder = new StringBuilder();

for (int i = 0; i < str.length(); i++) {
char current = str.charAt(i);

boolean isDuplicate = false;

for (int j = 0; j < stringBuilder.length(); j++) {
if (stringBuilder.charAt(j) == current) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
stringBuilder.append(current);
}
}
return stringBuilder.toString();
}
}

0 comments on commit d291beb

Please sign in to comment.