C#C
C#3y 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;
            }
        }
`

And I am confused with this line
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
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.
Was this page helpful?