算法-字符串的去重

字符串去重分3种情况
1、去掉重复的字符,并且只保留一个
2、去掉重复的字符,如果有多个的保留两个
3、去掉重复的字符,重复的一个都不保留

对应第一种情况的解法:
只需要对字符串进行遍历,如果遍历到重复的字符就跳过,如果遍历到不重复的就赋值
第二种:
需要在第一种情况下加一个判断bool变量,用于判断是否已经加了一个。
第三种:
还是判断当前遍历的位置和下一个位置进行判断,不过需要判断两次,因为如果有AACB这种字符串,当遍历到第二个A的时候下一个是C是不同的但是不知道C后面是不是还是C,所以第一次判断为true。下面进行第二次判断,如果C后面不是C就证明C是仅有的一个不是重复的。

第一种

void Remove_1(char * str){
	int index = 0;
	int pos = 1;
	while(str[pos] != '\0'){
		if(str[pos] != '\0'){
			index++;
			str[index] = str[pos];	
		}
		pos++;
	}
	str[++index] = '\0';
}

测试效果
在这里插入图片描述

第二种

void Remove_2(char * str){
	int index = 0;
	int pos = 1;
	bool flag = false;
	while(str[pos] != '\0'){
		if(str[pos] != str[index]){
			index++;
			str[index] = pos;
			flag = true;
		}
		else{
			if(flag){
				index ++;
				str[index] = str[pos];
				flag = false;	
			}	
		}
		pos++;
	}
	str[++index] = '\0';
}

测试效果:
在这里插入图片描述
第三种

void Remove_3(char * str){
	int index = -1;
	int pos = 0;
	bool flag = false;
	for(pos = 0;str[pos] != '\0';pos++){
		if(str[pos] == str[pos+1]){
			flag = true;	
		}
		else{
			if(flag){
				flag = false;	
			}	
			else{
				str[++index] = str[pos];	
			}
		}
	}
	str[++index] = '\0';
}

测试效果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43635647/article/details/103560024