leetcode题解(1)

题目描述
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。

有效字符串需满足:
1 左括号必须用相同类型的右括号闭合。
2 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。

来源:力扣(LeetCode)

思路:明显用栈解决。


  • 自己的写法:
  1. C语言版

考虑到代码简洁性
1,我们使用数组栈(避免实现链栈中push,pop方法)
2,由于只有一个例程,数组栈中的top设置为局部变量(不放入结构体中)

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

执行结果:

  1. C++版
class Solution {
public:
    bool isValid(string s) {
        if(s.length()%2!=0) return false;//一但是奇数说明不是有效的括号
        map<char,char> wordbook;//建立哈希表
        wordbook.insert(map<char,char>::value_type(')','('));
        wordbook.insert(map<char,char>::value_type(']','['));
        wordbook.insert(map<char,char>::value_type('}','{'));
        stack<char> mystack;//建立栈
        for(int i=0;i<s.length();i++)
        {
            if(s[i]=='['||s[i]=='{'||s[i]=='(')//匹配到左括号
                mystack.push(s[i]);//放入栈中
            else if(s[i]==']'||s[i]=='}'||s[i]==')')//匹配到右括号
            {
                if(mystack.empty()) return false;
                //匹配到右括号,栈中应该存在左括号。否则就是无效的括号
                if(wordbook[s[i]]==mystack.top())//与栈顶元素进行匹配
                {
                    mystack.pop();//匹配成功删除栈顶元素
                    continue;
                }
                else return false;
            }
        }
        if(mystack.empty()) return true;//有效的括号到最后检测结束栈中应没有元素
        else return false;
    }
};

执行结果:

  1. python版
class Solution(object):
    def judge(self, s):
        d = {"(": 1, "[": 2, "{": 3,
             ")": -1, "]": -2, "}": -3
        }
        stack = []
        for i in s:
            if not stack or stack[-1][1] + d[i] != 0:
                stack.append([i, d[i]])
            elif stack[-1][1] + d[i] == 0:
                stack.pop()
        if not stack:
            return True
        else:
            return

参考后的写法

C语言实现

bool isValid(char * s){
    if (s == NULL || s[0] == '\0') return true;
    char *stack = (char*)malloc(strlen(s)+1); int top =0;
    for (int i = 0; s[i]; ++i) {
        if (s[i] == '(' || s[i] == '[' || s[i] == '{') stack[top++] = s[i];
        else {
            if ((--top) < 0)                      return false;//先减减,让top指向栈顶元素
            if (s[i] == ')' && stack[top] != '(') return false;
            if (s[i] == ']' && stack[top] != '[') return false;
            if (s[i] == '}' && stack[top] != '{') return false;
        }
    }
    return (!top);//防止“【”这种类似情况
}

执行结果:

python实现:

class Solution:
    def isValid(self, s: str) -> bool:
        dic = {'{': '}',  '[': ']', '(': ')', '?': '?'}
        stack = ['?']
        for c in s:
            if c in dic: stack.append(c)
            elif dic[stack.pop()] != c: return False 
        return len(stack) == 1

发布了11 篇原创文章 · 获赞 29 · 访问量 856

猜你喜欢

转载自blog.csdn.net/a13352912632/article/details/104048192