# C#LeetCode刷题之#844-比较含退格的字符串​​​​​​​（Backspace String Compare）

• 1 <= S.length <= 200
• 1 <= T.length <= 200
• S 和 T 只含有小写字母以及字符 ‘#’。

Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.

Input: S = “ab#c”, T = “ad#c”

Output: true

Explanation: Both S and T become “ac”.

Input: S = “ab##”, T = “c#d#”

Output: true

Explanation: Both S and T become “”.

Input: S = “a##c”, T = “#a#c”

Output: true

Explanation: Both S and T become “c”.

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 and T only contain lowercase letters and ‘#’ characters.

```public class Program {

public static void Main(string[] args) {
var S = "ab#c";

var res = BackspaceCompare(S, T);
Console.WriteLine(res);

S = "a#c";
T = "b#cd";

res = BackspaceCompare2(S, T);
Console.WriteLine(res);

}

private static bool BackspaceCompare(string S, string T) {
var stackS = GetStack(S);
var stackT = GetStack(T);
if(stackS.Count != stackT.Count) return false;
for(var i = 0; i < stackS.Count; i++) {
if(stackS.ElementAt(i) != stackT.ElementAt(i))
return false;
}
return true;
}

private static Stack<char> GetStack(string S) {
var stack = new Stack<char>();
foreach(var c in S) {
if(c == '#') {
if(stack.Count != 0) stack.Pop();
} else {
stack.Push(c);
}
}
return stack;
}

private static bool BackspaceCompare2(string S, string T) {
var sb1 = GetStringBuilder(S);
var sb2 = GetStringBuilder(T);
return sb1.ToString() == sb2.ToString();
}

private static StringBuilder GetStringBuilder(string S) {
var sb = new StringBuilder();
for(var i = 0; i < S.Length; ++i) {
if(S[i] == '#') {
if(sb.Length > 0) sb.Remove(sb.Length - 1, 1);
} else sb.Append(S[i]);
}
return sb;
}

}```

```True
False```

(2)