輸入: hello 輸出: helo
第一種實現: 不新開數組, 也就是原地去重.
#include <stdio.h>
#include <string.h>
void removeDuplicate(char str[]);
int main (void) {
char name[] = "hello";
removeDuplicate(name);
printf("%s\n", name);
return 0;
}
void removeDuplicate(char str[]) {
int len = strlen(str);
int p = 0;
int i;
int j;
for (i=0; i<len; i++) {
if (str[i] != '\0') {
str[p++] = str[i];
for (j=i+1; j<len; j++) {
if (str[i] == str[j]) {
str[j] = '\0';
}
}
}
}
str[p] = '\0';
}
上面的代碼一共出現了3次'\0', 前2次的'\0'沒有什么特殊含義, 可以替換成任何在所給字符串中
不會出現的字符. 最后一個'\0'則是C語言中特有的, 是字符串結束標志.
就是把所有重復的元素標記成'\0', 那么剩下的元素則是不重復的元素, 通過變量p, 把這些元素重新
添加到結果字符串中即可.
第二種實現: 新開數組實現.
#include <stdio.h>
#include <string.h>
void removeDuplicate(char str[], char res[]);
int main (void) {
char name[20] = "sdfsssww";
char res[20];
removeDuplicate(name, res);
printf("%s\n", res);
return 0;
}
void removeDuplicate(char str[], char res[]) {
int slen = strlen(str);
int rlen = 0;
int flag; // 元素重復標志
int i;
int j;
for (i=0; i<slen; i++) {
flag = 0;
for (j=0; j<rlen; j++) {
// 每次都把結果數組遍歷一遍, 與當前字符比較, 有重復
// 就標記為 1
if (res[j] == str[i]) flag = 1;
}
if (flag == 0) {
res[rlen++] = str[i];
}
}
res[rlen] = '\0';
}
第三種, 一層循環, 開個ASCII數組進行標記
#include <stdio.h>
#include <string.h>
void removeDuplicate(char str[]);
int main (void) {
char name[] = "wwwwsssspp";
removeDuplicate(name);
printf("%s\n", name);
return 0;
}
void removeDuplicate(char str[]) {
int len = strlen(str);
int ascii[128] = {0};
int p = 0;
int i;
for (i=0; i<len; i++) {
if (ascii[str[i]] == 0) {
ascii[str[i]] = 1;
str[p++] = str[i];
}
}
str[p] = '\0';
}
第四種, 也是新開ASCII數組進行標記, 實現去2重, 比如輸入: sswqswww, 輸出: sswqsw
#include <stdio.h>
#include <string.h>
void removeDuplicate(char str[]);
int main (void) {
char name[] = "sswqswww";
removeDuplicate(name);
printf("%s\n", name);
return 0;
}
void removeDuplicate(char str[]) {
int len = strlen(str);
int ascii[128] = {0};
int p = 0;
int i;
for (i=0; i<len; i++) {
if (ascii[str[i]] != 2) {
ascii[str[i]]++;
str[p++] = str[i];
}
}
str[p] = '\0';
}
第五種, 上面的代碼簡單改下, 既可以實現去n重
#include <stdio.h>
#include <string.h>
void removeDuplicate(char str[], int n)
int main (void) {
char name[] = "sswqswww";
removeDuplicate(name, 2);
printf("%s\n", name);
return 0;
}
void removeDuplicate(char str[], int n) {
int len = strlen(str);
int ascii[128] = {0};
int p = 0;
int i;
for (i=0; i<len; i++) {
if (ascii[str[i]] != n) {
ascii[str[i]]++;
str[p++] = str[i];
}
}
str[p] = '\0';
}