How to find the largest valid sequence of brackets and brackets in a string?

So I have a script I need to write, and one of the biggest problems comes down to finding the largest valid subsequence within the string. Therefore i have something like

"()(({}[](][{[()]}]{})))(" 

as input and I will need to return

"[{[()]}]{}" 

as a conclusion.

I tried using a stack similar to a structure, as if you were in brackets, but couldn't figure out what works. I would prefer a solution in python, but any guide that can offer will help regardless of language. Efficiency should ideally be better than n ^ 2, since I can think of a solution to O (n ^ 2) using this How to find the correctness of a string of parentheses, curly braces and square brackets? and just try it on different substrings

+4
source share
3 answers

. , , . i, + 1: i, , /. , .

Python, :

def longest_valid(s):
    match = [0] * (len(s) + 1)
    for i in xrange(1, len(s)):
        if s[i] in '({[':
            continue
        open = '({['[')}]'.index(s[i])]
        start = i - 1 - match[i - 1]
        if start < 0: continue
        if s[start] != open: continue
        match[i] = i - start + 1 + match[start - 1]
    best = max(match)
    end = match.index(best)
    return s[end + 1 - best:end + 1]

print longest_valid("()(({}[](][{[()]}]{})))(")
print longest_valid("()(({}[]([{[()]}]{})))(")
print longest_valid("{}[()()()()()()()]")

O (n) .

+1

. - , (.

Input:  ()(({}[]([{[()]}]{})))(
Output: ()(({}[]([{[()]}]{})))

1 - . : (), [] {}. , .

()(({}[]([{[()]}]{})))(
11  2233    44   55

2 - . : . [{[()]}]. , , , . . 4 , 4.

()(({}[]([{[()]}]{})))(
11  2233 4444444455

3 - . , ,

()(({}[]([{[()]}]{})))(
11  2222 4444444444

2, . 4 , 4 .

()(({}[]([{[()]}]{})))(
11  2222444444444444

3,

()(({}[]([{[()]}]{})))(
11  2222222222222222

2,

()(({}[]([{[()]}]{})))(
1122222222222222222222

()(({}[]([{[()]}]{})))(
1111111111111111111111

, , . - .


:

, O(n) / . ( - O(1)). ​​ start end.

array[start-1] array[end+1], , , start/end.

. , , , .

/ , . /, . , / . , .

+1

, : ++ for while

, Regex ( )

, :

  • ,

, - - :

\[[^]]*\{.*\}

re.compile Python, . . * ( char) [^]] ( ), w + d + / Regex, .

0

Source: https://habr.com/ru/post/1650605/


All Articles