Algorithm/Algorithm__Codility-Python

Lesson7 - Brackets

말하는감자 2022. 6. 20. 21:31

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 ")".

 

def solution(S):
    # write your code in Python 3.6
    if len(S) == 0:
        return 1

    if len(S) == 1:
        return 0
    
    stack =[]
    for i in range(0, len(S)):
        if S[i] == "(" or S[i] == "{" or S[i] == "[":
            stack.append(S[i])
        else:
            if len(stack) == 0:
                return 0
            last = stack.pop()
            if S[i] == ")" and last != "(":
                return 0
            elif S[i] == "}" and last != "{":
                return 0
            elif S[i] == "]" and last != "[":
                return 0
    
    if len(stack) != 0:
        return 0
    
    return 1

 

 

'Algorithm > Algorithm__Codility-Python' 카테고리의 다른 글

Lesson2 - OddOccurrencesInArray  (0) 2022.06.21
Lesson2 - CyclicRotation  (0) 2022.06.21
Lesson1 - Binary Gap  (0) 2022.06.21
Lesson7 - Nesting  (0) 2022.06.20
Lesson7 - Fish  (0) 2022.06.20