It is quite easy, actually. The Algorithm to do this is listed below -
1) Create an empty stack and push -1 to it. The first element of stack is used to provide base for next valid string.
2) Initialize result as 0.
3) If the character is '(' i.e. str[i] == '('), push index 'i' to the stack.
a) Pop an item from stack
b) If stack is not empty, then find length of current valid sub string by taking difference between current index and top of the stack. If current length is more than result, then update the result.
c) If stack is empty, push current index as base for next valid sub string.
5) Return result.