Advertisement
Guest User

Untitled

a guest
May 27th, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.47 KB | None | 0 0
  1. '''This solution takes O(n) time and O(1) space
  2.  
  3. First, let's traverse the string from the beginning to the end and count the number
  4. of opening and closing brackets. As far as we realize that open_counter == close_counter,
  5. we need to recalculate the longest balanced parentheses length (simply it is equal to
  6. the overall number of brackets we've seen so far). If we realize that we've observed more
  7. closing brackets than opening ones, it means that the current subsequence is not valid and
  8. we need to make open_counter = close_counter = 0.
  9.                                                                
  10. Second, we need to repeat the process, but traverse the string in the opposite direction paying
  11. attention to the fact, that now we consider ')' brackets as 'opening' and '(' as closing.
  12. '''
  13.  
  14.                                                                
  15. def traverse_parentheses(parentheses, is_forward):
  16.     '''Returns the length of the longest contiguous substring of balanced parentheses
  17.    after one pass (forward or backward). This function is made to avoid code repetition
  18.    while doing nearly the same during forward and backward parentheses traverse.
  19.    
  20.    Args:
  21.        parentheses (str): string with brackets (may contain only '(' or ')')
  22.        is_forward (bool): if True we do forward traversing (from first element to the last),
  23.                           otherwise backward traversing (from the last to the first)
  24.    Return:
  25.        int: the length of the longest valid parentheses after the traverse
  26.    '''
  27.     if is_forward:
  28.         open_bracket = '('
  29.         close_bracket = ')'
  30.     else:
  31.         open_bracket = ')'
  32.         close_bracket = '('
  33.         parentheses = parentheses[::-1]
  34.        
  35.     open_cnt = 0 # counter for opening brackets
  36.     close_cnt = 0 # counter for closing brackets
  37.     longest_parentheses = 0
  38.  
  39.     for bracket in parentheses:
  40.         if bracket == open_bracket:
  41.             open_cnt += 1
  42.         if bracket == close_bracket:
  43.             close_cnt += 1
  44.         if open_cnt == close_cnt:
  45.             longest_parentheses = max(2 * open_cnt, longest_parentheses)
  46.         elif close_cnt > open_cnt:
  47.             open_cnt = close_cnt = 0
  48.            
  49.     return longest_parentheses
  50.            
  51.            
  52. def get_longest_balanced_parentheses(parentheses):
  53.     '''Returns the length of the longest contiguous substring of balanced parentheses.
  54.    Parentheses are considered balanced when there is a valid closing parenthesis for an opening one.
  55.    
  56.    Args:
  57.        parentheses (str): string with brackets (may contain only '(' or ')')
  58.    Return:
  59.        int: the length of the longest valid parentheses
  60.    '''
  61.     return max(
  62.         traverse_parentheses(parentheses, True), # forward traversing
  63.         traverse_parentheses(parentheses, False) # backward traversing
  64.     )
  65.  
  66.  
  67. # Tests
  68. assert get_longest_balanced_parentheses('()') == 2
  69. assert get_longest_balanced_parentheses('()()') == 4
  70. assert get_longest_balanced_parentheses('(())') == 4
  71. assert get_longest_balanced_parentheses('())') == 2
  72. assert get_longest_balanced_parentheses(')()(') == 2
  73.  
  74. assert get_longest_balanced_parentheses('') == 0
  75. assert get_longest_balanced_parentheses('))))((((') == 0
  76. assert get_longest_balanced_parentheses('(') == 0
  77. assert get_longest_balanced_parentheses(')') == 0
  78. assert get_longest_balanced_parentheses('(((((') == 0
  79.  
  80. for n in [100, 1000, 100000]:
  81.     assert get_longest_balanced_parentheses('(' * n + ')' * n) == 2 * n
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement