LeetCode -- Valid Parentheses
I have adopted two solutions for this topic. The first solution has fewer lines of code, but the efficiency is slightly lower. The second solution has more lines of code to be improved by referring to the online solution, but the efficiency is slightly higher.
Question: Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "() [] {}" are all valid but "(]" and "([)]" are not.
Solution 1:
Import java. util. HashMap; import java. util. Map; public class Solution {public boolean isValid (String s) {Map
Map = new HashMap
(); Map. put (']', '['); map. put ('}', '{'); map. put (')', '('); Stack
St = new Stack
(); For (int I = 0; I
Solution 2:
import java.util.HashMap;import java.util.Map;public class Solution { public boolean isValid(String s) { Stack
st = new Stack
(); for (int i = 0; i < s.length(); i++) { Character c = s.charAt(i); if ((c == ']') || (c == '}') || (c == ')')) { if (st.empty()) { return false; } Character pre = st.peek(); switch (c) { case ')': if (pre == '(') { st.pop(); } else { return false; } break; case '}': if (pre == '{') { st.pop(); } else { return false; } break; case ']': if (pre == '[') { st.pop(); } else { return false; } break; } } else { st.push(c); } } return st.empty() ? true : false; }}