Created
December 15, 2016 08:29
-
-
Save philipjkim/b76b494a271e0c8da35a982f3340b933 to your computer and use it in GitHub Desktop.
Removing duplicated chararters in char[]
This file contains hidden or 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
package org.sooo; | |
public class Ch1 { | |
public static char[] removeDup(char[] str) { | |
if (str == null || str.length == 1) { | |
return str; | |
} | |
// mark duplicated characters to special character (a.k.a. dupChar). | |
char dupChar = '\0'; | |
int dupCount = 0, i = 0; | |
while (i < str.length) { | |
if (str[i] == dupChar) { | |
i++; | |
continue; | |
} | |
for (int j=i+1;j<str.length;j++) { | |
if (str[i] == str[j]) { | |
str[j] = dupChar; | |
dupCount++; | |
} | |
} | |
i++; | |
} | |
// make a new array except dupChar. | |
char[] result = new char[str.length - dupCount]; | |
i = 0; | |
for(char c : str) { | |
if (c != dupChar) { | |
result[i] = c; | |
i++; | |
} | |
} | |
return result; | |
} | |
static void print(char[] str) { | |
if (str == null) { | |
System.out.println("null"); | |
return; | |
} | |
for (char c : str) { | |
System.out.print(c); | |
} | |
System.out.println(); | |
} | |
public static void main(String[] args) { | |
print(Ch1.removeDup(null)); | |
print(Ch1.removeDup(new char[]{'a'})); | |
print(Ch1.removeDup(new char[]{'a', 'b'})); | |
print(Ch1.removeDup(new char[]{'a', 'b', 'a'})); | |
print(Ch1.removeDup(new char[]{'a', 'b', 'c', 'b', 'a'})); | |
print(Ch1.removeDup(new char[]{'a', 'a', 'a', 'a', 'a'})); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment