Advertisement
satishfrontenddev4

Untitled

Jan 5th, 2024
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. You are given a string s, consisting of lowercase letters. You need to make duplicate removal on s until you no longer can.
  3.  
  4.  
  5. A duplicate removal consists of choosing two adjacent equal characters and removing both of them.
  6. Return the final string after all such duplicate removals have been made.
  7. Input format
  8. The first line contains a single string s.
  9.  
  10. Output format
  11. Print the final string after duplicate removals.
  12.  
  13. Function definition
  14. You have to complete the given function. It accepts one argument -the input string, and returns the updated string.
  15.  
  16. Sample Input 1
  17. abbaca
  18.  
  19. Sample Output 1
  20. ca
  21.  
  22. Explanation
  23. Initial String: abbaca
  24.  
  25. After removing "bb" : aaca
  26.  
  27. After removing "aa" : ca (There are no more duplicates)
  28.  
  29. Constraints
  30. 1 <= |s| <= 10^5
  31. */
  32.  
  33. /**
  34.  * @param {String} str
  35.  * @return {String}
  36.  */
  37. function removeAdjacentDuplicates(str) {
  38.     let stack=[];
  39.     let ans='';
  40.     for(let i=0;i<str.length;i++){
  41.         let curr=str.charAt(i);
  42.         if(stack.length!=0&&stack[stack.length-1]==curr){
  43.             stack.pop();
  44.         }
  45.         else{
  46.             stack.push(curr);
  47.         }
  48.     }
  49.     ans=stack.join('');
  50.     return ans;
  51. }
  52.  
  53. function main() {
  54.     let s = readLine();
  55.     let result = removeAdjacentDuplicates(s);
  56.     console.log(result);
  57. }
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement