Skip to content

Commit ad1e42c

Browse files
Merge pull request TheAlgorithms#60 from varunu28/master
Create removeDuplicateFromString.java
2 parents 370b988 + 542f687 commit ad1e42c

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

removeDuplicateFromString.java

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

0 commit comments

Comments
 (0)