```
public class Solution {
public int longestValidParentheses(String s) {
int total = 0;
int i = 0, k = 0;
int start = -1; int end = 0;
int answer = 0, maxAnswer = 0;
Map<Character, Integer> value = new HashMap<Character, Integer>();
value.put('(', 1);
value.put(')', -1);
if (s.charAt(0) == '(') {
s = ")" +s;
}
while(k < s.length()){
total += value.get(s.charAt(i));
if (total == -1) {
start = i;
total = 0;
k = i;
}
if (total == 0){
if (start > -1) {
answer = i - start;
maxAnswer = answer > maxAnswer? answer: maxAnswer;
}
}
i++;
if (i == s.length()) {
k++;
i = k;
}
}
return maxAnswer;
}
```

}