leetcode.com/problems/valid-parentheses/

 

Valid Parentheses - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.

  2. Open brackets must be closed in the correct order

Input: s = "()[]{}"
Output: true
class Solution {
	private HashMap<Character, Character> mappings;

	public Solution() {
		mappings = new HashMap<Character, Character>();
		mappings.put(')', '(');
		mappings.put(']', '[');
		mappings.put('}', '{');
	}

	public boolean isValid(String s) {
		Stack<Character> stack = new Stack<>();

		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);

			if (mappings.containsKey(c)) {
				char topChar = stack.empty() ? 'X' : stack.pop();

				if (topChar != mappings.get(c)) {
					return false;
				}
			} else {
				stack.push(c);
			}
		}

		return stack.isEmpty();
	}
}

'개발자 > algorithm' 카테고리의 다른 글

HackerRank, Binary Numbers (Java)  (0) 2021.01.25
백준 19279번 : 최대 힙 (java)  (0) 2021.01.12
LeetCode, Rotate Image (Java)  (0) 2021.01.08
LeetCode, Permutation (Java)  (0) 2021.01.07
LeetCode, Maximum Subarray (Java)  (0) 2021.01.06

+ Recent posts