출처:https://leetcode.com/problems/valid-parentheses/description/
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
- Every close bracket has a corresponding open bracket of the same type.
해석: 문자 '(', ')', '{', '}', '[', ']'만을 포함하는 문자열 s가 주어졌을 때, 입력 문자열이 유효한지 판단하세요.
입력 문자열이 유효하려면 다음 조건을 만족해야 합니다:
1.열린 괄호는 같은 종류의 괄호로 닫혀야 합니다.
2.열린 괄호는 올바른 순서로 닫혀야 합니다.
3.모든 닫힌 괄호는 같은 종류의 대응하는 열린 괄호가 있어야 합니다.
/**
* suedo code
* 함수 isValid(문자열 s):
* 스택 생성
* 괄호_매핑 = {')':'(', '}':'{', ']':'['}
*
* 각 문자 c에 대해 s를 순회:
* 만약 c가 열린 괄호라면:
* 스택에 c를 push
* 그렇지 않으면:
* 만약 스택이 비어있거나 스택의 pop 요소가 괄호_매핑[c]와 다르다면:
* false 반환
*
* 스택이 비어있는지 확인하여 결과 반환
*/
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for(char c: s.toCharArray()){
if(c=='('||c=='{'||c=='['){
stack.push(c);
}else{
if(stack.isEmpty())
return false;
else{
char top = stack.pop();
if((c==')'&& top!='(')||
(c=='}'&& top !='{')||
(c==']'&& top!='[')){
return false;
}
}
}
}
return stack.isEmpty();
}
}
'【스터디노트】 > ▶알고리즘문제풀기' 카테고리의 다른 글
[Best Time to Buy and Sell Stock] (0) | 2025.03.29 |
---|---|
[Merge Two Sorted Lists] (0) | 2025.03.27 |
[twoSum] (0) | 2025.03.26 |
[스택과 큐] (0) | 2025.03.26 |
[알고리즘] 위상정렬 (0) | 2025.02.28 |