Removing elements between the two zeros
Last Updated :
07 Oct, 2022
Given an integer N which shows the size of the string and in the next line given a string which contains a string of character with only zero and one. The task is to remove a single character each time that comes in between the two zero characters.
During each turn, only one character from the string will be removed that satisfies the following condition :
- It must be surrounded by zeroes on both sides.
Examples:
Input : str = “1001
Output : str = “1001”
Input : str = “10101
Output : str = “1001”
Use a loop from 1 to N – 1 and check if any element lies between two zeros such that s[i – 1] = ‘0’ and s[i + 1] = ‘0’. If the condition is satisfied then, delete the character at that position, ad start searching for patterns again.
C++
#include <bits/stdc++.h>
using namespace std;
string findstring(string s)
{
int n = s.length();
for ( int i = 1; i < n - 1; i++)
{
if ((s.at(i - 1) == '0' &&
s.at(i + 1) == '0' ))
{
s.erase(i, 1);
i--;
if (i > 0 && s.at(i - 1) == '0' )
i--;
n = s.length();
}
}
return s;
}
int main() {
cout << findstring( "100100" );
return 0;
}
|
Java
import java.util.*;
public class GFG
{
static String findstring(String s)
{
int n = s.length();
for ( int i = 1 ; i < n - 1 ; i++)
{
if ((s.charAt(i - 1 ) == '0' &&
s.charAt(i + 1 ) == '0' ))
{
s = s.substring( 0 , i) + s.substring(i + 1 );
i--;
if (i > 0 && s.charAt(i - 1 ) == '0' )
i--;
n = s.length();
}
}
return s;
}
public static void main(String[] args)
{
String s= "100100" ;
System.out.println(findstring(s));
}
}
|
Python3
def findstring(s):
n = len (s)
s = list (s)
i = 1
while i < n - 1 :
if (s[i - 1 ] = = '0' and
s[i + 1 ] = = '0' ):
s.pop(i)
i - = 1
if i > 0 and s[i - 1 ] = = '0' :
i - = 1
n = len (s)
i + = 1
return ''.join(s)
if __name__ = = '__main__' :
print (findstring( '100100' ))
|
C#
using System;
class GFG
{
static string findstring( string s)
{
int n = s.Length;
string st = "" ;
for ( int i = 1; i < n - 1; i++)
{
if ((s[i - 1] == '0' &&
s[i + 1] == '0' ))
{
st = s.Remove(i, 1);
s = st;
i--;
if (i > 0 &&
s[i - 1] == '0' )
i--;
n = s.Length;
}
}
return s;
}
static void Main()
{
Console.Write(findstring( "100100" ));
}
}
|
Javascript
<script>
function findstring(s){
let n = s.length
s = s.split( '' )
let i = 1
while (i < n - 1){
if (s[i - 1] == '0' && s[i + 1] == '0' ){
s.splice(i,1);
i -= 1
if (i > 0 && s[i - 1] == '0' )
i -= 1
n = s.length
}
i += 1
}
return s.join( '' )
}
document.write(findstring( '100100' ), "</br>" )
</script>
|
Time Complexity: O(N2), where N is the size of the input string and using erase function to delete the value in the string.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...