From d291beb47f5ff8548a082ff7ae59b447a8ae2391 Mon Sep 17 00:00:00 2001 From: Vishwajeet-29-pro Date: Fri, 6 Dec 2024 08:06:26 +0530 Subject: [PATCH] feat: Add method RemoveDuplicatesCharacters from string --- .../strings/RemoveDuplicatesCharacters.java | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 JavaDsaWithTest/src/main/java/org/practice/dsa/strings/RemoveDuplicatesCharacters.java diff --git a/JavaDsaWithTest/src/main/java/org/practice/dsa/strings/RemoveDuplicatesCharacters.java b/JavaDsaWithTest/src/main/java/org/practice/dsa/strings/RemoveDuplicatesCharacters.java new file mode 100644 index 0000000..a4fd7dc --- /dev/null +++ b/JavaDsaWithTest/src/main/java/org/practice/dsa/strings/RemoveDuplicatesCharacters.java @@ -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 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(); + } +}