import java.util.Scanner; import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 String s = in.next(); int n = s.length() - 2; Deque<Character> stk = new ArrayDeque<>(); for (char ch: s.toCharArray()) { if (ch != '(' && ch != ')') continue; if (ch == '(') stk.push(ch); else if (ch == ')'){ if (!stk.isEmpty() && stk.peek() == '(') stk.pop(); else stk.push(ch); } } System.out.println(n - stk.size()); } }
双指针方法做 import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * @param s string字符串 * @return int整型 */ public int longestValidParentheses (String s) { // write code here int l=0,r=s.length()-1; Stack<Character> sk1=new Stack<>(); int len=0; while(l<r){ if(s.charAt(l)=='('){ sk1.add('('); } l++; if(s.charAt(r)==')'){ if(!sk1.isEmpty()){ len+=2; r--; } }else r--; } return len; } }