Given a string S containing letters and ‘#‘. The ‘#” represents a backspace. The task is to print the new string without ‘#‘.
Examples:
Input : S = "abc#de#f#ghi#jklmn#op#"
Output : abdghjklmo
Input : S = "##geeks##for##geeks#"
Output : geefgeek
Approach: A simple approach to this problem by using deque is as follows:
- Traverse the string S.
- If any character except ‘#’ is found push it at back in deque.
- if the character ‘#’ is found pop a character from back of deque.
- Finally pop all elements from front of deque to make new string.
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
string newString(string S)
{
deque< char > q;
for ( int i = 0; i < S.length(); ++i) {
if (S[i] != '#' )
q.push_back(S[i]);
else if (!q.empty())
q.pop_back();
}
string ans = "" ;
while (!q.empty()) {
ans += q.front();
q.pop_front();
}
return ans;
}
int main()
{
string S = "##geeks##for##geeks#" ;
cout << newString(S);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static String newString(String S)
{
Stack<Character> q = new Stack<Character>();
for ( int i = 0 ; i < S.length(); ++i)
{
if (S.charAt(i) != '#' )
q.push(S.charAt(i));
else if (!q.isEmpty())
q.pop();
}
String ans = "" ;
while (!q.isEmpty())
{
ans += q.pop();
}
String answer = "" ;
for ( int j = ans.length() - 1 ; j >= 0 ; j--)
{
answer += ans.charAt(j);
}
return answer;
}
public static void main(String[] args)
{
String S = "##geeks##for##geeks#" ;
System.out.println(newString(S));
}
}
|
Python3
def newString(S):
q = []
for i in range ( 0 , len (S)):
if S[i] ! = '#' :
q.append(S[i])
elif len (q) ! = 0 :
q.pop()
ans = ""
while len (q) ! = 0 :
ans + = q[ 0 ]
q.pop( 0 )
return ans
if __name__ = = "__main__" :
S = "##geeks##for##geeks#"
print (newString(S))
|
C#
using System.Collections.Generic;
using System;
class GFG
{
static String newString(String S)
{
Stack<Char> q = new Stack<Char>();
for ( int i = 0; i < S.Length; ++i)
{
if (S[i] != '#' )
q.Push(S[i]);
else if (q.Count!=0)
q.Pop();
}
String ans = "" ;
while (q.Count!=0)
{
ans += q.Pop();
}
String answer = "" ;
for ( int j = ans.Length - 1; j >= 0; j--)
{
answer += ans[j];
}
return answer;
}
public static void Main(String []args)
{
String S = "##geeks##for##geeks#" ;
Console.WriteLine(newString(S));
}
}
|
Javascript
<script>
function newString(S)
{
let q = [];
for (let i = 0; i < S.length; ++i)
{
if (S[i] != '#' )
q.push(S[i]);
else if (q.length!=0)
q.pop();
}
let ans = "" ;
while (q.length!=0)
{
ans += q.pop();
}
let answer = "" ;
for (let j = ans.length - 1; j >= 0; j--)
{
answer += ans[j];
}
return answer;
}
let S = "##geeks##for##geeks#" ;
document.write(newString(S)+ "<br>" );
</script>
|
Complexity Analysis:
- Time Complexity: O(N), where N is the length of the String.
- Space Complexity: O(N) since using auxiliary deque