删除字符串中连续的重复字符_从字符串中删除连续的重复项

删除字符串中连续的重复字符

Constraints:

限制条件:

    (length of string) < 10000

Example:

例:

    Sample Input 1:
    bbccbb
    
    Sample Output 1:
    After removing consecutive duplicates, the answer is :: bcb

    Sample Input 2:
    aabccbba

    Sample Output 2:
    After removing consecutive duplicates, the answer is :: abcba

Explanation of the problem:

问题说明:

  1. Find the length of the input string and create an empty string to the answer and add the first character of the input string to the answer string.

    找到输入字符串的长度,并为答案创建一个空字符串,然后将输入字符串的第一个字符添加到答案字符串。

  2. Store the 0th character of the string in one character variable (let's name it as first) to store the duplicate character that has already added to the answer string.

    将字符串的第0个字符存储在一个字符变量中(让我们以第一个命名),以存储已经添加到答案字符串中的重复字符。

  3. Start iterating from the first index to the end of the input string.

    从第一个索引开始迭代到输入字符串的末尾。

  4. If the current character is different from stored duplicate variable then add it to our answer string and make the current character as a duplicate character.

    如果当前字符与存储的重复变量不同,则将其添加到我们的答案字符串中,并使当前字符成为重复字符。

  5. After the whole string has been iterated, return the answer string.

    重复整个字符串后,返回答案字符串。

The time complexity of the above code is O(length of string).

上面代码的时间复杂度是O(字符串的长度)。

C++ Implementation

C ++实现

#include <iostream>
#include <string>
using namespace std;

string removeduplicates(string s){
	int n = s.length();
	string ans = "";
	// Adding the first character to the ans
	ans = ans + s[0];
	// first is the character to keep the track of included character
	char first = s[0];
	for(int i = 1;i<n;i++){
		// ch is the current character
		char ch = s[i];
		/* if already included character is different from our 
		current character then add current character to the ans
		and assign current character to included character */
		if(ch != first){
			ans = ans + s[i];
			first = s[i];
		}       
	}
	return ans;
}

// Driver programm to check the code
int main() {
	string s1 ;
	cout<<"Enter string: ";
	cin >>s1;
	cout<<"Entered string is: "<<s1<<endl;	
	cout<<"After removing consecutive duplicates, string: " << removeduplicates(s1) << endl;
}

Output

输出量

Enter string: bbccbb
Entered string is: bbccbb
After removing consecutive duplicates, string: bcb


翻译自: https://www.includehelp.com/algorithms/removing-consecutive-duplicates-from-a-string.aspx

删除字符串中连续的重复字符

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值