Location>code7788 >text

Stack, a structure that specializes in handling temporary data

Popularity:910 ℃/2024-09-19 11:35:10

catalogs
  • Practice 1 -- Removing asterisks from strings


Stacks and arrays store data in the same way; they are both just lists of elements.The difference lies in the following 3 limitations of the stack

  • Data can only be inserted from the end of the stack;
  • Data can only be deleted from the end of the stack;
  • Only the last element of the stack can be read.

a wooden or bamboo pen for sheep or cattlecap (a poem)formationarray sth.Same. All of them.abstract data structure
What is an abstract data structure? It refers to a form of data organization that is not concerned with concrete implementation details, but rather focuses on the logical structure and operations of data. In computer science, an abstract data structure defines how data is organized and what operations are permitted, but does not specify the specifics of how these operations are implemented in a computer.

In short, the stack in many programming languages do not have a specific implementation, you can be in the array of the basis of their own to the array plus the three previously mentioned restrictions on the use of the use of the array, use, then the array is what you want the stack.

Practice 1 -- Removing asterisks from strings

Title requirements
image

Problem Solving Ideas:
Consider using a stack to help solve this problem, as the last-in-first-out (LIFO) nature of stacks is well suited to this need.

Then consider the two positions of the * sign:

  • *a
  • a*

They correspond to the following two stack processing flows. Let's first look at the A * position processing flow:
Reads the first coordinate of the
image
Read the second coordinate, pop off the stack element
image
Reading the third coordinate, the
image
reading the fourth coordinate.
image

Look again at * the processing flow for the A position:
First reading.
image

Second reading.
image

Third read, flag -= 1.
image

Fourth reading.
image

Fifth reading.
image

Code reference.
The code isn't very optimized, it just implements the functionality.

class Solution:
    def removeStars(self, s: str) -> str:
        index_letters = []
        flag = 0
        for i, v in enumerate(s):
            if v == "*":
                if len(index_letters) == 0:
                    flag += 1
                if len(index_letters) >= 1:
                    flag -= 1
                    index_letters.pop()
            if v != "*":
                index_letters.append(v)

            if len(index_letters) >= 1:
                for i in range(flag):
                    if (len(index_letters) != 0):
                        index_letters.pop()
                        flag -= 1

        newStr = ""
        for v1 in index_letters:
            newStr += v1
        return newStr


s = Solution()
s2 = "leet**cod*e"
s1 = "**o*d*ety"
print((s2))