844. 比较含退格的字符串

844. 比较含退格的字符串

给定 S 和 T 两个字符串,当它们分别被输入到空白的文本编辑器后,判断二者是否相等,并返回结果。 # 代表退格字符。

注意:如果对空文本输入退格字符,文本继续为空。

 

示例 1:

  输入:S = "ab#c", T = "ad#c"
  输出:true
  解释:S 和 T 都会变成 “ac”。
示例 2:

  输入:S = "ab##", T = "c#d#"
  输出:true
  解释:S 和 T 都会变成 “”。
示例 3:

  输入:S = "a##c", T = "#a#c"
  输出:true
  解释:S 和 T 都会变成 “c”。
示例 4:

  输入:S = "a#c", T = "b"
  输出:false
  解释:S 会变成 “c”,但 T 仍然是 “b”。
 

#include<iostream>
#include<stack>
#include <algorithm>
#include<cstring>
using namespace std;
string backspaceCompare(string &str){
     stack<char> st;
     int len =str.length();
     for (int i = 0; i < len; i++)
     {
         if (str[i]=='#'&&!st.empty())
             st.pop();
         if (str[i]!='#')
             st.push(str[i]);
     }
     string strs="";
     while (!st.empty())
     {
        strs.push_back(st.top());
        st.pop();
     }
     reverse(strs.begin(),strs.end());
     return strs;
}
int main(){
    stack<char> st1,st2;
    string  str1,str2;
    cin>>str1>>str2;
    str1=backspaceCompare(str1);
    str2=backspaceCompare(str2);
    // cout<<str1<<endl<<str2<<endl;
    if (str1==str2)
    {
        cout<<"true"<<endl;
    }else
    {
        cout<<"false"<<endl;
    }
}

 

因上求缘,果上努力~~~~ 作者:每天卷学习,转载请注明原文链接:https://www.cnblogs.com/BlairGrowing/p/13515364.html

原文地址:https://www.cnblogs.com/BlairGrowing/p/13515364.html