Skip to content

Instantly share code, notes, and snippets.

@zac-xin
Created April 18, 2012 11:32
Show Gist options
  • Save zac-xin/2413013 to your computer and use it in GitHub Desktop.
Save zac-xin/2413013 to your computer and use it in GitHub Desktop.
1.3 Design an algorithm and write code to remove the duplicate characters in a string without using any additional buffer.
public class RemoveDuplicates {
public static void main(String args[]){
String s = "1234512345aabbbccccddddddeeefffffggg";
char[] input = s.toCharArray();
removeDup(input);
System.out.println(input);
}
public static void removeDup(char[] data){
int len = data.length;
if(len < 2)
return;
int i,j;
int tail = 1;
/* 从0到tail-1的位置都是已经确认过没有duplicates的
* 在某一个i的for循环中 j是从0到tail-1 如果发现data[i] == data[j]
* 那么data[i]可以直接舍弃
* 否则 j最后会等于tail 表明data[i]不等于 0到tail-1中的任意元素
* 就可以将data[i]放到data[tail]的位置上 tail++
* 最后将tail到len-1的值都设为'\0'
*
* 如果一直没有duplicates i和tail是一起增加的
* 如果有duplicates tail就会暂时停止增加
* 最后只保留0-tail的数据
*/
for(i = 1; i < len; i++){
for(j = 0; j < tail; j++){
if(data[i] == data[j])
break;
}
if(j == tail){
data[tail] = data[i];
tail++;
}
}
for(i = tail; i < len; i++)
data[i] = '\0';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment