-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Add method RemoveDuplicatesCharacters from string
- Loading branch information
1 parent
9a4d9bc
commit d291beb
Showing
1 changed file
with
45 additions
and
0 deletions.
There are no files selected for viewing
45 changes: 45 additions & 0 deletions
45
JavaDsaWithTest/src/main/java/org/practice/dsa/strings/RemoveDuplicatesCharacters.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} | ||
} |