I am looking over some code in Java here:
public String Build(String Str) {
Stack<Character> result = new Stack();
for (char x: Str.toCharArray()) {
if (x != '$')
result.push(x);
else
result.pop();
}
return String.valueOf(result); // Does C# have an equivalent for this?
}
Here's the working solution I wrote in C#, but I was wondering if theres an easier method?
public string Build(string s) {
Stack stack = new Stack();
foreach (char x in s.ToCharArray()) {
if (x != '$') {
stack.Push(x);
}
else
stack.Pop();
}
string result = String.Empty;
while (stack.Count != 0) { // In C#, I loop and store the value in a string.
result += stack.Peek();
stack.Pop();
}
return result;
}
Is there a better method in C# that would be similar to the first method posted in Java? I understand the method in C# is returning the string backwards, but that does not matter for the functionality of this method.