leetcode 1190. 反轉每對括號間的子串

用棧解決就行, 遇到右括號,就反轉再塞回去。

class Solution {
    public String reverseParentheses(String s) {
        Stack<Character> stack = new Stack<>();
        int top = 0;
        List<Character> tmp = new ArrayList<Character>();
        for(char c : s.toCharArray()) {
            if(c == ')'){
                int i = 0;
                char topC;
                while(stack.peek() != '('){
                    topC = stack.pop();
                    tmp.add(topC);
                }
                stack.pop();
                
                for(Character tmpc : tmp){
                    stack.push(tmpc);
                }
                tmp.clear();
            }
            else{
                stack.push(c);
            }
        }
        
        StringBuilder sb = new StringBuilder();
        while(!stack.isEmpty()){
            tmp.add(stack.pop());
        }
        
        for(int i = tmp.size()-1; i >=0;i--){
            sb.append(tmp.get(i));
        }
        return sb.toString();
    }
}

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章