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. ThreadLocal(在一个线程中共享数据)

    ThreadLocal 在"事务传递Connection"参数案例中,我们必须传递Connection对象,才可以完成整个事务操作.如果不传递参数,是否可以完成?在JDK中给我们提 ...

  2. hive日期转换函数2

    转自大神 http://www.oratea.net/?p=944 无论做什么数据,都离不开日期函数的使用. 这里转载一下Hive的日期函数的使用,写的相当完整. 日期函数UNIX时间戳转日期函数: ...

  3. MAT022 Foundations of Statistics

    MAT022 Foundations of Statistics and Data Science Summative Assessment 2019/20MAT022 Foundations of ...

  4. 解读 v8 排序源码

    前言 v8 是 Chrome 的 JavaScript 引擎,其中关于数组的排序完全采用了 JavaScript 实现. 排序采用的算法跟数组的长度有关,当数组长度小于等于 10 时,采用插入排序,大 ...

  5. 斜率优化板题 HDU2829 Lawrence

    题目大意:给定一个长度为nnn的序列,至多将序列分成m+1m+1m+1段,每段序列都有权值,权值为序列内两个数两两相乘之和.求序列权值和最小为多少? 数据规模:m<=n<=1000.m&l ...

  6. Codeforces Round #605 (Div. 3) E. Nearest Opposite Parity(最短路)

    链接: https://codeforces.com/contest/1272/problem/E 题意: You are given an array a consisting of n integ ...

  7. jeecg uedit 自定义图片上传路径

    jeecg uedit 图片上传配置自定义物理路径,简单描述:我们知道 jeecg 中使用的 uedit 默认图片上传路径为 "当前项目\plug-in\ueditor\jsp\upload ...

  8. 【洛谷P4319】 变化的道路 线段树分治+LCT

    最近学了一下线段树分治,感觉还蛮好用... 如果正常动态维护最大生成树的话用 LCT 就行,但是这里还有时间这一维的限制. 所以,我们就把每条边放到以时间为轴的线段树的节点上,然后写一个可撤销 LCT ...

  9. circus security 来自官方的安全建议

    转自:https://circus.readthedocs.io/en/latest/design/security/ Circus is built on the top of the ZeroMQ ...

  10. Codevs 3322 时空跳跃者的困境(组合数 二项式定理)

    3322 时空跳跃者的困境 时间限制: 1 s 空间限制: 64000 KB 题目等级 : 钻石 Diamond 题目描述 Description 背景:收集完能量的圣殿战士suntian开始了他的追 ...