codeforces(yahua and paranthesis-1097C

Although time complexity doesnt seem to be a problem but still the time limit gets exceeded for very long strings. Can someone help?
question link-https://codeforces.com/contest/1097/problem/C
solution link-https://ideone.com/e.js/sLApJq

//