package RemoveDuplicaeCharFromSttring;
import java.util.LinkedHashSet;
import java.util.Set;
public class RemoveDuplicateCharFromString {
public static String removeDuplicateCharsFromSring(String inputSring) {
if (inputSring == null || inputSring.isEmpty()) {
return inputSring;
}
// A LinkedHashSet stores unique characters and maintains insertion order.
Set<Character> seen = new LinkedHashSet<>();
// Use a StringBuilder for efficient string building.
StringBuilder result = new StringBuilder();
// Iterate through the input string
for (char ch : inputSring.toCharArray()) {
// If the character is not already in the set, add it to both the set and the result string
if (seen.add(ch)) {
result.append(ch);
}
}
// Convert the StringBuilder to a String and return
return result.toString();
}
public static void main(String[] args) {
String input1 = "programming";
String output1 = removeDuplicateCharsFromSring(input1);
System.out.println("Original String: " + input1);
System.out.println("After removing dulicate chars: " + output1);
}
}
Comments
Post a Comment