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

有效字符串需满足:

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

(1)可能出现的情况:

  (1)"()"

  (2)"()[]"

  (3)"(])]"

  (4)"((([]))"

  (5)"]][["

(2) 时间复杂度

进栈出栈O(1),一次性操作,每个元素都会进行一次这样此操作,所以O(1)*n

(3)实现

c版本

 bool isValid(char * s){
if (s == NULL || s[] == '\0') return true;
char *stack = (char*)malloc(strlen(s)+); int top =;
for (int i = ; s[i]; ++i) {
if (s[i] == '(' || s[i] == '[' || s[i] == '{') stack[top++] = s[i];
else {
if ((--top) < ) 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(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack=[]
paren_map={')':'(',']':'[','}':'{'}
for c in s:
if c not in paren_map:
stack.append(c)
elif not stack or paren_map[c]!=stack.pop():
return False
return not stack

2 用栈实现队列---leetcode232

思路:使用两个栈s1,s2,s2不为空则从s1去除放入s2,s2不为空弹出

 class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() { } /** Push element x to the back of queue. */
void push(int x) {
s1.push(x);
} /** Removes the element from in front of queue and returns that element. */
int pop() {
if(s2.empty())
{
while(!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
}
int ans=s2.top();
s2.pop();
return ans;
} /** Get the front element. */
int peek() {
if(s2.empty())
while(!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
int ans = s2.top();
return ans;
} /** Returns whether the queue is empty. */
bool empty() {
return s1.empty()&&s2.empty(); }
public:
stack<int>s1;
stack<int>s2;
}; /**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/

3 用队列实现栈

思路:

  C++实现,用一个队列即可实现,只用将n-1队尾元素拿出来头插,再出队尾元素,或是删除队尾元素,即可实现一个栈先进后出的功能

 class MyStack {
public:
/** Initialize your data structure here. */
MyStack() { } /** Push element x onto stack. */
void push(int x) {
q1.push(x);
} /** Removes the element on top of the stack and returns that element. */
int pop() {
int size=q1.size()-;
for(size_t i=;i<size;++i)
{
q1.push(q1.front());
q1.pop();
}
int front=q1.front();
q1.pop();
return front;
} /** Get the top element. */
int top() {
return q1.back();
} /** Returns whether the stack is empty. */
bool empty() {
if(q1.empty())
{
return true;
}else
return false;
}
private:
queue<int>q1;
}; /**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/

面试之leetcode20堆栈-字符串括号匹配,队列实现栈的更多相关文章

  1. Valid Parentheses有效括号匹配。利用栈。

    问题描述:给定一个字符串,其中只包含字符‘{’,    '}',    '[',    ']',   '(',    ')'确定如果输入字符串是有效的.括号必须以正确的顺序排列,“()”和“()[]{ ...

  2. 利用栈实现括号匹配(python语言)

    原理: 右括号总是与最近的左括号匹配 --- 栈的后进先出 从左往右遍历字符串,遇到左括号就入栈,遇到右括号时,就出栈一个元素与其配对 当栈为空时,遇到右括号,则此右括号无与之匹配的左括号 当最终右括 ...

  3. 括号匹配问题(C++、堆栈)

    原文地址:http://www.cppblog.com/GUO/archive/2010/09/12/126483.html /* 括号匹配问题,比较经典,利用堆栈来实现(摘自internet) 1. ...

  4. YTU 3003: 括号匹配(栈和队列)

    3003: 括号匹配(栈和队列) 时间限制: 1 Sec  内存限制: 128 MB 提交: 2  解决: 2 [提交][状态][讨论版] 题目描述 假设一个表达式中只允许包含三种括号:圆括号&quo ...

  5. OJ——华为编程题目:输入字符串括号是否匹配

    package t0815; /* * 华为编程题目:输入字符串括号是否匹配 * 若都匹配输出为0,否则为1 * 样例输入:Terminal user [name | number (1)] * 样例 ...

  6. C++学习(三十一)(C语言部分)之 栈和队列(括号匹配示例)

    括号匹配测试代码笔记如下: #include<stdio.h> #include<string.h> #include <stdlib.h> #define SIZ ...

  7. python栈--字符串反转,括号匹配

    栈的实现: # 定义一个栈类 class Stack(): # 栈的初始化 def __init__(self): self.items = [] # 判断栈是否为空,为空返回True def isE ...

  8. SDUT-2134_数据结构实验之栈与队列四:括号匹配

    数据结构实验之栈与队列四:括号匹配 Time Limit: 1000 ms Memory Limit: 65536 KiB Problem Description 给你一串字符,不超过50个字符,可能 ...

  9. 华为笔试题--LISP括号匹配 解析及源码实现

    在17年校招中3道题目AC却无缘华为面试,大概是华为和东华互不待见吧!分享一道华为笔试原题,共同进步! ************************************************ ...

随机推荐

  1. STM32L4R9使用HAL库调试IIC注意事项

    STM32使用Cubemx生成的代码中,用到IIC的驱动,但是始终不能读写,因此使用逻辑分析仪,发现原本地址为0x58的写成了0x20,因此肯定是地址错了.因此,总结如下: 1.需要逻辑分析仪分析II ...

  2. circus && web comsole docker-compose 独立部署web console 的一个bug

    如果直接使用以下的docker-compose 文件部署会有通过多播通信获取endpoint 异常的问题(circus 在stats endpoint 获取少了一个c) 这个问题是部分网络情况下会出现 ...

  3. vue关于keep-alive的小坑

    在移动端里 少不了底部导航 在做底部导航的时候点击都会重复请求 我就使用了keep-alive来缓存 每次点击的时候走缓存 这里还有个用途就是当有列表的时候点进详情在返回可以保存之前的滚动记录 不会刷 ...

  4. [译博文]CUDA是什么

    翻译自:https://blogs.nvidia.com/blog/2012/09/10/what-is-cuda-2/ 你可能并没有意识到,GPU的应用有多广泛,它不但用于视频.游戏以及科学研究中, ...

  5. siblings() 方法

    siblings([selected])       简介: 给定一个表示一组DOM元素的jQuery对象,该.siblings()方法允许我们在DOM树中搜索这些元素的兄弟节点,并从匹配的元素构造一 ...

  6. HDU 1542.Atlantis-线段树求矩形面积并(离散化、扫描线/线段树)-贴模板

    好久没写过博客了,这学期不是很有热情去写博客,写过的题也懒得写题解.现在来水一水博客,写一下若干年前的题目的题解. Atlantis Time Limit: 2000/1000 MS (Java/Ot ...

  7. Linux查看当前操作系统版本信息

    .Linux查看当前操作系统版本信息 cat /proc/version Linux version -.el6.x86_64 (mockbuild@c1bm.rdu2.centos.org) (gc ...

  8. mysql left()函数

    mysql> select * from test; +----+------------+-------+-----------+ | id | name | score | subject ...

  9. mysql5.7设置默认的字符集

    修改/etc/my.cnf文件 一.在[mysqld]下添加: default-storage-engine=INNODB character-set-server=utf8 collation-se ...

  10. FormData实现文件上传

    我用到FormData传输的使用场景:vant UI组件里面 的图片上传这块,需要调用后台的图片上传接口,使用的是FormData方式上传的 https://www.cnblogs.com/hutuz ...