|
1 | 1 | package com.thealgorithms.others;
|
2 | 2 |
|
3 |
| -import java.io.BufferedReader; |
4 |
| -import java.io.InputStreamReader; |
5 |
| - |
6 | 3 | /**
|
7 | 4 | * @author Varun Upadhyay (https://github.com/varunu28)
|
8 | 5 | */
|
9 | 6 | public final class RemoveDuplicateFromString {
|
10 | 7 | private RemoveDuplicateFromString() {
|
11 | 8 | }
|
12 | 9 |
|
13 |
| - public static void main(String[] args) throws Exception { |
14 |
| - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
15 |
| - String inpStr = br.readLine(); |
16 |
| - |
17 |
| - System.out.println("Actual string is: " + inpStr); |
18 |
| - System.out.println("String after removing duplicates: " + removeDuplicate(inpStr)); |
19 |
| - |
20 |
| - br.close(); |
21 |
| - } |
22 |
| - |
23 | 10 | /**
|
24 |
| - * This method produces a string after removing all the duplicate characters |
25 |
| - * from input string and returns it Example: Input String - "aabbbccccddddd" |
26 |
| - * Output String - "abcd" |
| 11 | + * Removes duplicate characters from the given string. |
27 | 12 | *
|
28 |
| - * @param s String from which duplicate characters have to be removed |
29 |
| - * @return string with only unique characters |
| 13 | + * @param input The input string from which duplicate characters need to be removed. |
| 14 | + * @return A string containing only unique characters from the input, in their original order. |
30 | 15 | */
|
31 |
| - public static String removeDuplicate(String s) { |
32 |
| - if (s == null || s.isEmpty()) { |
33 |
| - return s; |
| 16 | + public static String removeDuplicate(String input) { |
| 17 | + if (input == null || input.isEmpty()) { |
| 18 | + return input; |
34 | 19 | }
|
35 | 20 |
|
36 |
| - StringBuilder sb = new StringBuilder(); |
37 |
| - int n = s.length(); |
38 |
| - |
39 |
| - for (int i = 0; i < n; i++) { |
40 |
| - if (sb.toString().indexOf(s.charAt(i)) == -1) { |
41 |
| - sb.append(s.charAt(i)); |
| 21 | + StringBuilder uniqueChars = new StringBuilder(); |
| 22 | + for (char c : input.toCharArray()) { |
| 23 | + if (uniqueChars.indexOf(String.valueOf(c)) == -1) { |
| 24 | + uniqueChars.append(c); // Append character if it's not already in the StringBuilder |
42 | 25 | }
|
43 | 26 | }
|
44 | 27 |
|
45 |
| - return sb.toString(); |
| 28 | + return uniqueChars.toString(); |
46 | 29 | }
|
47 | 30 | }
|
0 commit comments