- 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 cattle
cap (a poem)formation
、array 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
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
Read the second coordinate, pop off the stack element
Reading the third coordinate, the
reading the fourth coordinate.
Look again at * the processing flow for the A position:
First reading.
Second reading.
Third read, flag -= 1.
Fourth reading.
Fifth reading.
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))