Algorithm Study - 001

2021. 6. 2. 17:42·Algorithm/JAVA

Problem


https://leetcode.com/problems/valid-parentheses/

 

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.

먼저 적힌 괄호는 나중에 닫히는 이른바 FILO 방식의 알고리즘을 요구하는 문제.

Stack이 제일 먼저 떠오른다면 반은 먹고 들어갔다고 할 수 있다.

 

Solution


class Solution {
    public boolean isValid(String s) {
        Map<Character, Character> map = new HashMap<>();
        Stack<Character> stack = new Stack<>();
        
        map.put(')','(');
        map.put(']','[');
        map.put('}','{');
        
        for(Character c : s.toCharArray()) {
            if(c == '(' || c == '[' || c == '{') {
                stack.push(c);
            }else if(stack.isEmpty() || stack.pop() != map.get(c)) {
                return false;
            }
        }
                
        return stack.isEmpty();
    }
}

Map과 Stack을 이용한 소스.

더욱 최적화가 가능해 보이지만 이 이상의 퍼포먼스 차이는 체감이 어려울 것으로 판단.

 

Constraints:

  • 1 <= s.length <= 104
  • s consists of parentheses only '()[]{}'.

제약 조건은 위와 같으므로 s.length가 0일 경우 Exception code는 생략.

 

Learn Point


1. Map의 of 사용법, 위의 소스에서는 없지만 아래처럼 쓸 수 있다. 가독성은 잘 모르겠지만 뭔가 간결해보인다.

class Solution {
    public boolean isValid(String s) {
        Map<Character, Character> map = Map.of(')', '(', ']', '[', '}', '{');
        Stack<Character> stack = new Stack<>();
        
        for(Character c : s.toCharArray()) {
            if(c == '(' || c == '[' || c == '{') {
                stack.push(c);
            }else if(stack.isEmpty() || stack.pop() != map.get(c)) {
                return false;
            }
        }
                
        return stack.isEmpty();
    }
}

2. Stack의 FILO 특징과 push, pop, peek 와 같은 함수 (Map의 get도 역시)들에 대한 리마인딩

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

Algorithm Study - 003  (0) 2021.06.03
Algorithm Study - 002  (0) 2021.06.02
숫자 반전 알고리즘  (0) 2021.06.02
'Algorithm/JAVA' 카테고리의 다른 글
  • Algorithm Study - 003
  • Algorithm Study - 002
  • 숫자 반전 알고리즘
seowooJeong
seowooJeong
  • seowooJeong
    개발일기
    seowooJeong
  • 전체
    오늘
    어제
    • 분류 전체보기 (25)
      • FrontEnd (6)
      • BackEnd (6)
      • Project (6)
      • Algorithm (4)
        • JAVA (4)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
    • React
    • Spring
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    jenkins gitlab
    QueryDSL 오류
    jenkinsfile
    collection 리스트
    jQuery
    build.gradle querydsl
    Java
    resultmap 리스트
    숫자 알고리즘
    mybatis list
    spring msa cicd
    intellij querydsl
    resultmap 중첩
    gitlab ci/cd
    숫자 거꾸로
    jenkinsfile 설정
    숫자 반전
    jeknins 파이프라인
    Spring QueryDsl
    querydsl 환경설정
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
seowooJeong
Algorithm Study - 001
상단으로

티스토리툴바