C
C#14mo ago
morry329#

❔ Why is Pop() necessary here??

So I found a sample solution for the LeetCode decode string puzzle https://leetcode.com/problems/decode-string/
public class Solution
{
public string DecodeString(string s)
{
Stack<string> strings = new Stack<string>();
Stack<int> numbers = new Stack<int>();

string currentString = "";
int currentNumber = 0;

foreach (char c in s)
{
if (c == '[')
{
strings.Push(currentString);
numbers.Push(currentNumber);
currentString = "";
currentNumber = 0;
}
else if(c == ']')
currentString = strings.Pop() + string.Join("", Enumerable.Repeat(currentString, numbers.Pop()));
else if ( c-'0'<=9 && c - '0' >= 0)
currentNumber = currentNumber * 10 + (c - '0');
else
currentString += c;
}

return currentString;
}
}
public class Solution
{
public string DecodeString(string s)
{
Stack<string> strings = new Stack<string>();
Stack<int> numbers = new Stack<int>();

string currentString = "";
int currentNumber = 0;

foreach (char c in s)
{
if (c == '[')
{
strings.Push(currentString);
numbers.Push(currentNumber);
currentString = "";
currentNumber = 0;
}
else if(c == ']')
currentString = strings.Pop() + string.Join("", Enumerable.Repeat(currentString, numbers.Pop()));
else if ( c-'0'<=9 && c - '0' >= 0)
currentNumber = currentNumber * 10 + (c - '0');
else
currentString += c;
}

return currentString;
}
}
` And I am confused with this line
currentString = strings.Pop() + string.Join("", Enumerable.Repeat(currentString, numbers.Pop()));
currentString = strings.Pop() + string.Join("", Enumerable.Repeat(currentString, numbers.Pop()));
` Why is it strings.Pop() needed here?? ChatGPT says it's not needed and it's redundant, I do not think that is the correct answer. Does the Pop remove the bracket [, so the code goes on to check part of the string??
LeetCode
LeetCode - The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
4 Replies
phaseshift
phaseshift14mo ago
Debug it and watch
Tvde1
Tvde114mo ago
Stack.Pop Method (System.Collections)
Removes and returns the object at the top of the Stack.
Tvde1
Tvde114mo ago
Removes and returns the object at the top of the Stack.
Accord
Accord14mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server