Week 11
Today I did another leetcode problem. Like last week I found a similar problem to one I've done in class but with a different language but instead of mips this time it is in C++. I'm starting to think my 240 teacher was making us do these problems on purpose haha... anyway, the problem this time is called valid parenthesis or matching brackets is what my 240 teacher called it. I knew the basic rundown of the problem and tried to code it. But to give a brief rundown we are checking if all brackets "(" or "{" or "[" are closed correctly. Fortunately, I was able to directly translate the code for the most part, so we can see the tiny differences between c++ and java.
We see in the two pictures below that c++ looks a little different. In java we see the stack as new stack but in C++ #include stack and we dont need to new. In C++ the string as treated a char arrays so we dont need to do charAt in C++ they already are characters and in this respect it is much easier. In java we use peek but in C++ its top. Big difference is that in this problem for C++ I had to have a main and take in a file and see if it has matching brackets. The cout and cin is still super weird though and using the << or >> to take the data in. I also took at "<" and ">" because we dont need to look for those in this problem.
What the C++ code does it is has a Boolean method that takes a string of data and checks if the brackets are matching. To accomplish this is initializes a stack runs a for loop for however long the string (array of characters) is. While the loop is running we check if the pointer that goes through each char of the string and once it finds an open bracket it pushes it on the stack. Once it is pushed on we check through the string to find the ending and once we find that ending we check to see if the most recently pushed character is the beginning bracket of the ending if it isn't then its false. In the switch to get the top we set c ,which will hold are character and check it with the current character we are on in the string, then we pop it off to move on because we already have the top(which is what gets popped) saved. We then check the pop and see if its either of the ones we don't want and if it is, its false. We do that for the others and once we are done we return the Boolean method empty(), which will be true if it works. In java its very similar we just do some extra typing for s.charAt to check the characters and java has the peek instead of the top method. It was cool to see how similar java and C++ are and to do the problem again by trying to remember what I did in my C++ code.
Comments
Post a Comment