Got stuck in this problem for one hour. I was trying to use a variable left to count the left parentheses. However, we should not only count the number of them, but also the position of them. Then we need to use stack.
There is a very elegant solution here (In Java): http://rleetcode.blogspot.com/2014/01/longest-valid-parentheses.html
This problem really cost me so much time. So I would like to post this for reviewing later.