Remove Consecutive Characters Geeks For Geeks

 class Solution{

    public String removeConsecutiveCharacter(String s){

        Stack<Character> stack=new Stack<Character>();

int count=0;

for(int i=0;i<s.length();i++){

if(stack.isEmpty()==true){

stack.push(s.charAt(i));

}

else if(String.valueOf(stack.peek()).equals(String.valueOf(s.charAt(i)))){

count++;

}

else

stack.push(s.charAt(i));

}

//System.out.println(stack);

StringBuffer sb=new StringBuffer();

while(!stack.isEmpty()){

    sb.append(stack.pop());

}

sb.reverse();

return sb.toString();

    }

}


APPROACH:

Here we will use a stack. We will add the elements of string in the stack in such a manner that if an element is equal to the peek of the stack it won't get added to the stack otherwise it will be added in the stack. I have used a counter variable also which will count the number of times different duplicate elements were traversed.

After that, we will add elements of the stack into StringBuffer and reverse it (as the stack is last in first out).

The reverse object will be converted to a string and will be returned. 


TIME:O(StringLength)[Traversing till StringLength][GFG Time: 0.5/3.2]

SPACE: <O(StringLength)[Using Stack and adding elements]

In the worst case, the space complexity will be O(N) when all elements are unique the stack size will be equal to the length of the string otherwise it will be less than the length of the string.



Thanks for Reading.😇


Comments

Post a Comment

Popular posts from this blog

Solutions Of Practice Questions Dated 01-06-2022

CODEFORCES SPY DETECTED ROUND 713

Maximum Winning Score Geeks For Geeks