Loliko_LinawZ

导航

 
20. 有效的括号
class Solution {
    public boolean isValid(String s) {
        Deque<Character> deque = new LinkedList<>();
        for(int i = 0; i < s.length(); i ++){
            char ch = s.charAt(i);
            if(ch == '('){
                deque.push(')');
            } else if(ch == '{'){
                deque.push('}');
            } else if(ch == '['){
                deque.push(']');
            } else if(deque.isEmpty() || deque.peek() != ch){
                return false;
            } else{
                deque.pop();
            }
        }

        return deque.isEmpty();
    }
}
View Code

1047. 删除字符串中的所有相邻重复项

class Solution {
    public String removeDuplicates(String s) {
        ArrayDeque<Character> deque = new ArrayDeque<>();
        char ch;
        for(int i = 0; i < s.length(); i ++){
            ch = s.charAt(i);
            if(deque.isEmpty() || deque.peek() != ch){
                deque.push(ch);
            } else{
                deque.pop();
            }
        }
        String str = "";
        while(!deque.isEmpty()){
            str = deque.pop() + str;
        }
        return str;
    }
}
View Code

 

 
posted on 2023-10-24 11:49  数码暴龙猪  阅读(4)  评论(0编辑  收藏  举报