반응형
Recent Posts
Recent Comments
관리 메뉴

개발잡부

[codility] Nesting 본문

이직

[codility] Nesting

닉의네임 2022. 7. 26. 11:26
반응형
A string S consisting of N characters is called properly nested if:

S is empty;
S has the form "(U)" where U is a properly nested string;
S has the form "VW" where V and W are properly nested strings.
For example, string "(()(())())" is properly nested but string "())" isn't.

Write a function:

class Solution { public int solution(String S); }

that, given a string S consisting of N characters, returns 1 if string 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..1,000,000];
string S consists only of the characters "(" and/or ")".
// you can also use imports, for example:
import java.util.*;

// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");

class Solution {
    public int solution(String S) {
        // write your code in Java SE 8
                Stack<Character> stack = new Stack<>();
        
        for (char c : S.toCharArray()){

            if(c =='('){
                stack.push(c);
            } else {

                if(stack.empty()) {
                    return 0;
                }

                if (c == '(' && stack.pop() != ')'){
                    return 0;
                }
                if (c == ')' && stack.pop() != '('){
                    return 0;
                }
            }

        }
        return stack.empty()? 1 : 0;
    }
}
반응형

'이직' 카테고리의 다른 글

TwoSum  (0) 2022.07.27
hadoop 준비  (1) 2022.07.27
[codility] Brackets  (0) 2022.07.25
[codility] NumberOfDiscIntersections  (0) 2022.07.25
[codility] Triangle  (0) 2022.07.25
Comments