본문 바로가기
Programming/Algorithm

[leetcode] ValidParentheses

by 읽고 쓰는 개발자 2020. 11. 29.

https://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

 

import java.util.Stack;

public class ValidParentheses {
    public static void main(String[] args) {
        System.out.println(isValid("{}[][](()){[[]]}"));
    }


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

        for(int i = 0 ; i < s.length(); i++) {
            char aa = s.charAt(i);
            if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') {
                  stack.push(s.charAt(i));
            } else {
                if(stack.size() ==0) return false;
                else if(s.charAt(i) == '}' && stack.pop() != '{') return false;
                else if(s.charAt(i) == ')' && stack.pop() != '(') return false;
                else if(s.charAt(i) == ']' && stack.pop() != '[') return false;
            }
        }

        return stack.size() == 0;
    }
}

 

'Programming > Algorithm' 카테고리의 다른 글

[leetcode] WordLadder  (0) 2020.11.29
[leetcode] WordDictionary  (0) 2020.11.29
[leetcode] ValidateBinarySearchTree  (0) 2020.11.29
[leetcode] RotateList  (0) 2020.11.29
[leetcode] RomanToInt  (0) 2020.11.29