删除字符串中连续的重复字符
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:
问题说明:
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.
找到输入字符串的长度,并为答案创建一个空字符串,然后将输入字符串的第一个字符添加到答案字符串。
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个字符存储在一个字符变量中(让我们以第一个命名),以存储已经添加到答案字符串中的重复字符。
Start iterating from the first index to the end of the input string.
从第一个索引开始迭代到输入字符串的末尾。
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.
如果当前字符与存储的重复变量不同,则将其添加到我们的答案字符串中,并使当前字符成为重复字符。
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
删除字符串中连续的重复字符