Skip to content

Latest commit

 

History

History
111 lines (84 loc) · 1.9 KB

20、有效的括号.md

File metadata and controls

111 lines (84 loc) · 1.9 KB

20、有效的括号

给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。

示例 1:

输入:s = "()"
输出:true

示例 2:

输入:s = "()[]{}"
输出:true

示例 3:

输入:s = "(]"
输出:false

示例 4:

输入:s = "([)]"
输出:false

示例 5:

输入:s = "{[]}"
输出:true

提示:

1 <= s.length <= 104 s 仅由括号 '()[]{}' 组成

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/valid-parentheses 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

c语言实现

bool isValid(char * s){
    int n = strlen(s);
    char a[n];
    int top = 0;
    a[top]=s[top];
    for(int i = 1;i<n;i++){
        top++;
        a[top]=s[i];
        if(top==0){continue;}
        else if(a[top-1]=='('&&a[top]==')'||a[top-1]=='['&&a[top]==']'||a[top-1]=='{'&&a[top]=='}'){
            top-=2;
        }
    }
    if(top==-1){
        return true;
    }else{
        return false;
    }
}

java实现

class Solution {
    public boolean isValid(String s) {
        char[] arr = s.toCharArray();
        int n = arr.length;
        char []a = new char[n];
        int top = 0;
        a[0] = arr[0];
        for(int i = 1;i<n;){
            top++;
            a[top]=arr[i];
            i++;
            if(top==0){continue;}
            else if(a[top-1]=='('&&a[top]==')'||a[top-1]=='['&&a[top]==']'||a[top-1]=='{'&&a[top]=='}'){
                top-=2;
            }
        }
        if(top==-1){
            return true;
        }else{
            return false;
        }
    }
}