How does Java judge whether the parentheses in a string are valid?
This article introduces the relevant knowledge of "how to judge whether the parentheses in a string are valid by Java". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Topic: judge whether the parentheses in the string are valid. Parentheses are required to appear in pairs and correspond to the order of parentheses. For example: [12 (fgsf) 4]-valid, {d [] df34}-valid, {f3 [aer)}-invalid, {3) 32}-invalid.
Idea: use for (char c: s) to operate on each element of a string, and Stack if c is "(", "[", "{"). If ")", "]", "}", the Stack operation is performed and compared to the stack.top () element, which, if paired, is valid.
Language: cpp
Class Solution {public:bool isValid (string's) {stack stk;for (char c: s) {switch (c) {case'(': case'[': case'{': stk.push (c); break;case')': if (stk.empty () | stk.top ()! ='(') return false;else stk.pop (); break;case']': if (stk.empty () | stk.top ()! ='[') return false;else stk.pop (); break Case'}': if (stk.empty () | | stk.top ()! ='{') return false;else stk.pop (); break;default:break;}} return stk.empty ();}}; "how does Java determine whether the parentheses in a string are valid?". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!