Given two strings S
and T
, return if they are equal when both are typed into empty text editors. #
means a backspace character.
Example 1:
Input: S = "ab#c", T = "ad#c" Output: true Explanation: Both S and T become "ac".
Example 2:
Input: S = "ab##", T = "c#d#" Output: true Explanation: Both S and T become "".
Example 3:
Input: S = "a##c", T = "#a#c" Output: true Explanation: Both S and T become "c".
Example 4:
Input: S = "a#c", T = "b" Output: false Explanation: S becomes "c" while T becomes "b".
Note:
-
1 <= S.length <= 200
-
1 <= T.length <= 200
-
S
andT
only contain lowercase letters and'#'
characters.
想法:使用两个栈,分别处理字符串S和字符串T。对于字符串S而言,逐个遍历该字符串,如果字符不为#,入栈,如果为#,则执行栈的pop()操作。对字符串T也执行同样的操作。最后再比较两个栈中元素是否相等即可
public: bool backspaceCompare(string S, string T) { std::stack<char> s; std::stack<char> t; for(char i : S){ if(i != '#'){ s.push(i); }else if(!s.empty() && i == '#'){ s.pop(); } } for(char j : T){ if(j != '#'){ t.push(j); }else if(!t.empty() && j == '#'){ t.pop(); } } return s == t; } };