반응형
https://app.codility.com/programmers/lessons/7-stacks_and_queues/brackets/
A string S consisting of N characters is considered to be properly nested if any of the following conditions is true:
S is empty;S has the form "(U)" or "[U]" or "{U}" where U is a properly nested string;S has the form "VW" where V and W are properly nested strings.
For example, the string "{[()()]}" is properly nested but "([)()]" is not.
Write a function:
class Solution { public int solution(String S); }
that, given a string S consisting of N characters, returns 1 if S is properly nested and 0 otherwise.
For example, given S = "{[()()]}", the function should return 1 and given S = "([)()]", the function should return 0, as explained above.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [0..200,000];string S consists only of the following characters: "(", "{", "[", "]", "}" and/or ")".
쉬운 문제입니다.
스택을 이용해서 처리 할 수 있습니다.
스택이 비어있으면 push를, 그리고 쌍일 경우에 pop을 합니다. 그리고 모든 스택이 비어있으면 1을 그렇지 않으면 0을 리턴합니다.
매우 간단한 구조입니다.
아래는 소스코드 입니다.
public class Brackets {
public int solution(String S) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < S.length(); i++) {
if (stack.isEmpty()) {
stack.push(S.charAt(i));
continue;
}
if ((stack.peek() == '(' && S.charAt(i) == ')')
|| (stack.peek() == '[' && S.charAt(i) == ']')
|| (stack.peek() == '{' && S.charAt(i) == '}')) {
stack.pop();
continue;
}
stack.push(S.charAt(i));
}
return stack.isEmpty() ? 1 : 0;
}
}
728x90
반응형
'Coding Test' 카테고리의 다른 글
[LeetCode] Number of Good Pairs (0) | 2022.03.21 |
---|---|
[LeetCode] Single Number (0) | 2021.09.17 |
[Codility] Algorithmic skills. FirstUnique (0) | 2021.08.13 |
[프로그래머스] 완전탐색. 수포자 (1) | 2021.08.12 |
[Hackerrank] Strings. Java String Reverse (0) | 2021.08.12 |