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. 用mingw32编译ffmpeg2.7

    1.  下载x265最新源码:      下载ffmpeg源码(我用的是2.7):      下载cmake最新版本并安装:      下载SDL(我用的SDL-1.2.15):      下载min ...

  2. winafl 源码分析

    前言 winafl 是 afl 在 windows 的移植版, winafl 使用 dynamorio 来统计代码覆盖率,并且使用共享内存的方式让 fuzzer 知道每个测试样本的覆盖率信息.本文主要 ...

  3. nginx和ftp搭建图片服务器

    一.需要的组件 图片服务器两个服务: Nginx(图片访问): 1.http服务:可以使用nginx做静态资源服务器.也可以使用apache.推荐使用nginx,效率更高. 2.反向代理 实现 负载均 ...

  4. sql语句的面试题

    中科软的面试题:http://www.mayiwenku.com/p-5888480.html 中科软的面试题:https://blog.csdn.net/woolceo/article/detail ...

  5. python操作json文件获取内容

    写case时,将case 写到json文件比写到,写python一定要学会处理json 以下,是要处理的json 处理操作包括:打开json文件,获取json文件内容,关闭json文件,读取内容中的对 ...

  6. How to change hostname on debian

    How to change hostname on Debian 10 Linux last updated July 13, 2019 in CategoriesDebian / Ubuntu, L ...

  7. 开源项目 02 HttpLib

    using JumpKick.HttpLib; using Newtonsoft.Json; using System; using System.Collections.Generic; using ...

  8. Generating a Random Sample from discrete probability distribution

    If is a discrete random variable taking on values , then we can write . Implementation of this formu ...

  9. linux命令之------Linux文件系统具体目录

    Linux文件系统具体目录 (1)/  Linux文件系统的入口,也是处于最高一级的目录 (2)/bin  系统所需要的那些命令处于此目录,比如Is,cp,mkdir等命令:功能和/usr/bin类似 ...

  10. javascript 中的方法注入

    js 中的方法注入 java中很多框架支持 apo 的注入, js中也可以类似的进行实现 主要是通过扩展js中方法的老祖 Function 对象来进行实现. Function.prototype.af ...