-1

For example input string:

s = "fo)o)fus()(bar((em)ro(em))dah((y(XXX)"

As a result I expect:

fus()((em)ro(em))dah(XXX)

It's like result should contain all "healthy" blocks, which has open "(" and closed ")" + "healthy" text between them. All sick parts should be removed: "fo)" and "o)" because they are not involved in "()" and they are not between "()" or are not included in "()"

One more example for check:

z = "))(OMG)123(()qwe(zxc)(ll"

should return (OMG)123()qwe(zxc)

I will that it can be resolved as with re module as regular script. But I have no idea which algorithm should be used.

PS: I will not refuse from any help. :)

Yuriy Leonov
  • 332
  • 1
  • 3
  • 22
  • What have you come up with so far? – Jan Mar 17 '17 at 14:54
  • I've tried to translate parentheses to increment/decrements numbers, map it with index and get parts which should be included. Like s = "fo)o)fus()(bar((em)ro(em))dah((y(XXX)" -1 -2 -1 -2 -1 0 1 0 1 0 -1 -2 -1 0 1 0 – Yuriy Leonov Mar 17 '17 at 14:56
  • and if go in reverse mode: when index increases from x to x+1 -> it should be added, else -> not – Yuriy Leonov Mar 17 '17 at 14:59

1 Answers1

1

There is very good example for using stacks and nearly every CS student solved this at least once. Check this as an example but you can find much better syntax (specially written for C++).

These solutions are usually for checking if the statement is correct or not, but you can use same logic to remove wrong parts and only save the ones that match. So just create new string variable (variable=""), iterate over string and check for parenthesis, if they are in correct place then add them to that variable. To check parenthesis order, use Stack object, when you will see opening parenthesis push that to the stack and then continue, when it will be closing one, then pop the last value from stack and check (new item is ) and last item in stack should be (). If they don't match, throw away that part and continue, if they match then add that part to string.

Community
  • 1
  • 1
Emin Mastizada
  • 1,197
  • 1
  • 13
  • 28
  • 1
    @EricDuminil yes, if you will make temporary string before adding it to main variable. In that case when the loop will and without parenthesis the temp will not be added to main string and so problem will be solved. So idea will be to collect all the string between parenthesis into temp and when parenthesis will be closed and it to main string, clean temp and continue the loop. – Emin Mastizada Mar 17 '17 at 15:14
  • Makes sense. Thanks! – Eric Duminil Mar 17 '17 at 15:15