Style
Java Code-style conventions put:
- the
{
brace at the end of the line that introduces the compound statement block, not on the next line.
- spaces between variables and operators:
for (int i=0;i<length;i++)
Your code should look like:
public static String removeDuplicate(String s) {
char[] temp = s.toCharArray();
int length = temp.length;
for (int i = 0; i < length; i++) {
for (int j = i + 1; j < length; j++) {
if (temp[i] == temp[j]) {
int test = j;
for (int k = j + 1; k < length; k++) {
temp[test] = temp[k];
test++;
}
length--;
j--;
}
}
}
return String.copyValueOf(temp).substring(0, length);
}
Algorithm
You have three nested loops. This is inefficient.
A slight nit-pick is that you also use an inefficient way to get the resulting String using the copyValueOf(...)
and then the substring(...)
.
I believe if you take an 'additive' approach to the process you will have a faster system. By extracting the onle loop in to a function it is also more readable:
private static final boolean foundIn(char[] temp, int size, char c) {
for (int i = 0; i < size; i++) {
if (temp[i] == c) {
return true;
}
}
return false;
}
public static String removeDuplicateY(String s) {
char[] temp = s.toCharArray();
int size = 0; //how many unique chars found so far
for (int i = 0; i < temp.length; i++) {
if (!foundIn(temp, size, temp[i])) {
// move the first-time char to the end of the return value
temp[size] = temp[i];
size++;
}
}
return new String(temp, 0, size);
}