Remove all continuous occurrences of ‘a’ and all occurrences of ‘b’
Last Updated :
24 Aug, 2023
Given a string str, the task is to remove all the continuous occurrences of a and all occurrences of b and print the resultant string.
Examples
Input: str = “abcddabcddddabbbaaaaaa”
Output: acddacdddda
‘abcddabcddddabbbaaaaaa’ will not result in ‘acddacddddaa’ because after removing the required occurrences, the string will become ‘acddacddddaa’ which will result in ‘acddacdddda’
Input: str = “aacbccdbsssaba”
Output: acccdsssa
Approach: We initialize an empty result string. We traverse the input string if the current character is b or current character is a and last character of result string is also a then ignore the character else push the character into the result string.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
string removeOccurrences(string str)
{
string res = "" ;
for ( int i = 0; i < str.size(); i++) {
if (str[i] == 'a' && res.back() == 'a' )
continue ;
else if (str[i] == 'b' )
continue ;
res = res + str[i];
}
return res;
}
int main()
{
string str = "abcddabcddddabbbaaaaaa" ;
cout << removeOccurrences(str);
return 0;
}
|
Java
class solution
{
static String removeOccurrences(String str)
{
String res = "" ;
for ( int i = 0 ; i < str.length(); i++) {
if (str.charAt(i) == 'a' && (res.length()== 0 ? ' ' :res.charAt(res.length()- 1 )) == 'a' )
continue ;
else if (str.charAt(i) == 'b' )
continue ;
res = res + str.charAt(i);
}
return res;
}
public static void main(String args[])
{
String str = "abcddabcddddabbbaaaaaa" ;
System.out.println(removeOccurrences(str));
}
}
|
Python3
def removeOccurrences( str ) :
res = ""
for i in range ( len ( str )) :
if (res) :
if ( str [i] = = 'a' and res[ - 1 ] = = 'a' ) :
continue
elif ( str [i] = = 'b' ) :
continue
else :
res + = str [i]
else :
if ( str [i] = = 'a' ) :
res + = str [i]
elif ( str [i] = = 'b' ) :
continue
else :
res + = str [i]
return res
if __name__ = = "__main__" :
str = "abcddabcddddabbbaaaaaa"
print (removeOccurrences( str ))
|
C#
using System;
class GFG
{
static String removeOccurrences(String str)
{
String res = "" ;
for ( int i = 0; i < str.Length; i++)
{
if (str[i] == 'a' && (res.Length==0? ' ' :
res[res.Length-1]) == 'a' )
continue ;
else if (str[i] == 'b' )
continue ;
res = res + str[i];
}
return res;
}
public static void Main(String []args)
{
String str = "abcddabcddddabbbaaaaaa" ;
Console.WriteLine(removeOccurrences(str));
}
}
|
Javascript
<script>
function removeOccurrences(str)
{
var res = "" ;
for ( var i = 0; i < str.length; i++) {
if (str.charAt(i) == 'a' &&
(res.length==0? ' ' :res.charAt(res.length-1)) == 'a' )
continue ;
else if (str.charAt(i) == 'b' )
continue ;
res = res + str.charAt(i);
}
return res;
}
var str = "abcddabcddddabbbaaaaaa" ;
document.write(removeOccurrences(str));
</script>
|
Time complexity: O(n), where n is the length of the input string. This is because the code iterates over each character of the string only once, performing constant time operations for each character.
Auxiliary Space: O(m), where m is the number of characters in the output string. This is because the code uses a single string to store the result, and the size of the result string is proportional to the number of characters that are not removed from the input string.
Another approach:
The idea is to push each character onto the stack while checking if the current character is equal to ‘a’ or ‘b’ and if the last character on the stack is also ‘a’. If so, we pop the ‘a’ from the stack before pushing the current character. If the current character is ‘b’, we simply skip pushing it onto the stack. Finally, we pop all the characters from the stack and append them to the result string.
Implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
string removeOccurrences(string str) {
stack< char > s;
string res;
for ( char c : str) {
if (c == 'b' ) {
continue ;
} else if (c == 'a' && !s.empty() && s.top() == 'a' ) {
s.pop();
} else {
s.push(c);
}
}
while (!s.empty()) {
res = s.top() + res;
s.pop();
}
return res;
}
int main() {
string str = "abcddabcddddabbbaaaaaa" ;
cout << removeOccurrences(str) << endl;
return 0;
}
|
Java
import java.util.*;
class Main {
static String removeOccurrences(String str) {
Stack<Character> s = new Stack<Character>();
String res = "" ;
for ( char c : str.toCharArray()) {
if (c == 'b' ) {
continue ;
} else if (c == 'a' && !s.empty() && s.peek() == 'a' ) {
s.pop();
} else {
s.push(c);
}
}
while (!s.empty()) {
res = s.peek() + res;
s.pop();
}
return res;
}
public static void main(String[] args) {
String str = "abcddabcddddabbbaaaaaa" ;
System.out.println(removeOccurrences(str));
}
}
|
Python3
def removeOccurrences(s: str ) - > str :
stack = []
res = ''
for c in s:
if c = = 'b' :
continue
elif c = = 'a' and stack and stack[ - 1 ] = = 'a' :
stack.pop()
else :
stack.append(c)
while stack:
res = stack.pop() + res
return res
str = "abcddabcddddabbbaaaaaa"
print (removeOccurrences( str ))
|
C#
using System;
using System.Collections.Generic;
class Program {
static string RemoveOccurrences( string str)
{
Stack< char > s = new Stack< char >();
string res = "" ;
foreach ( char c in str)
{
if (c == 'b' ) {
continue ;
}
else if (c == 'a' && s.Count > 0
&& s.Peek() == 'a' ) {
s.Pop();
}
else {
s.Push(c);
}
}
while (s.Count > 0) {
res = s.Peek() + res;
s.Pop();
}
return res;
}
static void Main( string [] args)
{
string str = "abcddabcddddabbbaaaaaa" ;
Console.WriteLine(RemoveOccurrences(str));
}
}
|
Javascript
function removeOccurrences(str) {
let s = [];
let res = "" ;
for (let i = 0; i < str.length; i++) {
let c = str[i];
if (c === 'b' ) {
continue ;
} else if (c === 'a' && s.length > 0 && s[s.length - 1] === 'a' ) {
s.pop();
} else {
s.push(c);
}
}
while (s.length > 0) {
res = s[s.length - 1] + res;
s.pop();
}
return res;
}
let str = "abcddabcddddabbbaaaaaa" ;
console.log(removeOccurrences(str));
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Approach Name: Using Two Pointers and String Concatenation
Steps:
- Initialize an empty string called result.
- Initialize two pointers i and j to 0.
- Iterate over the string from the first character to the second to last character:
a. If the current character is ‘a’ and the next character is not ‘a’, append the current character to result.
b. If the current character is not ‘a’, append the current character to result.
- If the last character is not ‘a’, append the last character to result.
- Replace all occurrences of ‘b’ in the result string with an empty string.
- Print the resulting string.
C++
#include <iostream>
#include <string>
#include <algorithm>
std::string remove_continuous_a_and_b(std::string str) {
std::string result = "" ;
int i = 0;
while (i < str.length() - 1) {
if (str[i] == 'a' && str[i+1] != 'a' ) {
result += str[i];
} else if (str[i] != 'a' ) {
result += str[i];
}
i++;
}
if (str[str.length() - 1] != 'a' ) {
result += str[str.length() - 1];
}
result.erase(std:: remove (result.begin(), result.end(), 'b' ), result.end());
return result;
}
int main() {
std::string input_str = "abcddabcddddabbbaaaaaa" ;
std::string result_str = remove_continuous_a_and_b(input_str);
std::cout << result_str << std::endl;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
public class Main {
public static String removeContinuousAAndB(String str) {
String result = "" ;
int i = 0 ;
while (i < str.length() - 1 ) {
if (str.charAt(i) == 'a' && str.charAt(i + 1 ) != 'a' ) {
result += str.charAt(i);
} else if (str.charAt(i) != 'a' ) {
result += str.charAt(i);
}
i++;
}
if (str.charAt(str.length() - 1 ) != 'a' ) {
result += str.charAt(str.length() - 1 );
}
result = result.replace( "b" , "" );
return result;
}
public static void main(String[] args) {
String inputStr = "abcddabcddddabbbaaaaaa" ;
String resultStr = removeContinuousAAndB(inputStr);
System.out.println(resultStr);
}
}
|
Python3
def remove_continuous_a_and_b( str ):
result = ""
i = 0
while i < len ( str ) - 1 :
if str [i] = = 'a' and str [i + 1 ] ! = 'a' :
result + = str [i]
elif str [i] ! = 'a' :
result + = str [i]
i + = 1
if str [ - 1 ] ! = 'a' :
result + = str [ - 1 ]
result = result.replace( 'b' , '')
return result
input_str = "abcddabcddddabbbaaaaaa"
result_str = remove_continuous_a_and_b(input_str)
print (result_str)
|
C#
using System;
class Program
{
static string RemoveContinuousAAndB( string str)
{
string result = "" ;
int i = 0;
while (i < str.Length - 1)
{
if (str[i] == 'a' && str[i + 1] != 'a' )
{
result += str[i];
}
else if (str[i] != 'a' )
{
result += str[i];
}
i++;
}
if (str[str.Length - 1] != 'a' )
{
result += str[str.Length - 1];
}
result = result.Replace( "b" , "" );
return result;
}
static void Main()
{
string input_str = "abcddabcddddabbbaaaaaa" ;
string result_str = RemoveContinuousAAndB(input_str);
Console.WriteLine(result_str);
}
}
|
Javascript
function removeContinuousAandB(str) {
let result = "" ;
let i = 0;
while (i < str.length - 1) {
if (str[i] === 'a' && str[i + 1] !== 'a' ) {
result += str[i];
}
else if (str[i] !== 'a' ) {
result += str[i];
}
i++;
}
if (str[str.length - 1] !== 'a ') {
result += str[str.length - 1];
}
// Remove all occurrences of ' b ' from the result using the ' replace ' method
result = result.replace(/b/g, ' ');
return result;
}
const inputStr = "abcddabcddddabbbaaaaaa" ;
const resultStr = removeContinuousAandB(inputStr);
console.log(resultStr);
|
Time Complexity: O(n) where n is the length of the input string. We iterate over the string once to create the resulting string and then perform a replace operation on it which takes linear time.
Auxiliary Space: O(n) where n is the length of the input string
Share your thoughts in the comments
Please Login to comment...