jayati

Backspace String Compare

Mar 26th, 2023
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.83 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     bool backspaceCompare(string s, string t) {
  4.         stack<char> s1;
  5.         stack<char> s2;
  6.  
  7.         for(char ch : s){
  8.  
  9.             if(ch == '#'){
  10.                 if(s1.empty())
  11.                     continue;
  12.                 s1.pop();
  13.             }else{
  14.                 s1.push(ch);
  15.             }
  16.         }
  17.  
  18.         for(char ch : t){
  19.  
  20.             if(ch == '#'){
  21.                 if(s2.empty())
  22.                     continue;
  23.                 s2.pop();
  24.             }else{
  25.                 s2.push(ch);
  26.             }
  27.         }
  28.  
  29.         while(!s1.empty() && !s2.empty()){
  30.             if(s1.top() != s2.top())
  31.                 return false;
  32.  
  33.             s1.pop();
  34.             s2.pop();
  35.         }
  36.  
  37.         if(!s1.empty() || !s2.empty())
  38.             return false;
  39.  
  40.         return true;
  41.     }
  42. };
Advertisement
Add Comment
Please, Sign In to add comment