public static String reverse(String str){ Stack<Character> stack = new Stack<>(); String s = ""; int len = str.length(); for(int i=0;i<len;i++){ char c = str.charAt(i); if(c!=')'){ stack.push(c); }else{ if(stack.isEmpty()){ return ""; } s = ""; while(!stack.isEmpty()&&stack.peek()!='('){ s+=stack.pop(); } if(stack.isEmpty()||stack.pop()!='('){ return ""; } int l = s.length(); for(int j=0;j<l;j++){ stack.push(s.charAt(j)); } } } s = ""; while(!stack.isEmpty()){ //注意不是s = s + stack.pop(); s = stack.pop()+ s; } return s; }