20. Valid Parentheses

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

一刷
题解:
一道基本的使用stack的题目。 Time Complexity - O(n), Space Complexity - O(n)

test case:
"){"
"([])"
"(("
public class Solution {
    public boolean isValid(String s) {
        if(s == null || s.length() == 0) return true;
        Stack<Character> stack = new Stack<Character>();
        for(int i=0; i<s.length(); i++){
            Character left = s.charAt(i);
            if(left == '(' || left == '[' || left == '{' )
                stack.push(left);
            else{
                if(stack.isEmpty()) return false;
                char cur = stack.pop();
                if(left == ']' && cur!='[') return false;
                else if(left == '}' && cur!='{') return false;
                else if(left == ')' && cur!='(') return false;
            }
        }
        
        if(!stack.isEmpty()) return false;
        return true;
    }
}

二刷

class Solution {
    public boolean isValid(String s) {
        if((s.length()&1)!=0) return false;
        Stack<Character> stack = new Stack();
        for(int i=0; i<s.length(); i++){
            char ch = s.charAt(i);
            if(ch == '[' || ch == '{' || ch == '(') stack.push(ch);
            else{
                if(stack.isEmpty()) return false;
                char pop = stack.pop();
                if((pop == '[' && ch == ']') 
                  || (pop == '(' && ch == ')') 
                  || (pop == '{' && ch == '}') ) continue;
                else return false;
            }
          
        }
        return stack.isEmpty();
    }
}

follow up: 如果不是括号,而是<html>这种标记符号呢?
可以依然用上述的方法,然后在stack push('h')

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容