zoukankan      html  css  js  c++  java
  • 面试之leetcode20堆栈-字符串括号匹配,队列实现栈

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

    有效字符串需满足:

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

    (1)可能出现的情况:

      (1)"()"

      (2)"()[]"

      (3)"(])]"

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

      (5)"]][["

    (2) 时间复杂度

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

    (3)实现

    c版本

     1 bool isValid(char * s){
     2     if (s == NULL || s[0] == '') return true;
     3     char *stack = (char*)malloc(strlen(s)+1); int top =0;
     4     for (int i = 0; s[i]; ++i) {
     5         if (s[i] == '(' || s[i] == '[' || s[i] == '{') stack[top++] = s[i];
     6         else {
     7             if ((--top) < 0)                      return false;//先减减,让top指向栈顶元素
     8             if (s[i] == ')' && stack[top] != '(') return false;
     9             if (s[i] == ']' && stack[top] != '[') return false;
    10             if (s[i] == '}' && stack[top] != '{') return false;
    11         }
    12     }
    13     return (!top);//防止“【”这种类似情况
    14 }
    View Code

    python版本

     1 class Solution(object):
     2     def isValid(self, s):
     3         """
     4         :type s: str
     5         :rtype: bool
     6         """
     7         stack=[]
     8         paren_map={')':'(',']':'[','}':'{'}
     9         for c in s:
    10             if c not in paren_map:
    11                 stack.append(c)
    12             elif not stack or paren_map[c]!=stack.pop():
    13                 return False
    14         return not stack
    View Code

    2 用栈实现队列---leetcode232

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

     1 class MyQueue {
     2 public:
     3     /** Initialize your data structure here. */
     4     MyQueue() {
     5         
     6     }
     7     
     8     /** Push element x to the back of queue. */
     9     void push(int x) {
    10         s1.push(x);
    11     }
    12     
    13     /** Removes the element from in front of queue and returns that element. */
    14     int pop() {
    15         if(s2.empty())
    16         {
    17             while(!s1.empty())
    18             {
    19                 s2.push(s1.top());
    20                 s1.pop();
    21             }
    22         }
    23         int ans=s2.top();
    24         s2.pop();
    25         return ans;
    26     }
    27     
    28     /** Get the front element. */
    29     int peek() {
    30         if(s2.empty())  
    31             while(!s1.empty())
    32             {
    33                 s2.push(s1.top());
    34                 s1.pop();
    35             }
    36         int ans = s2.top();
    37         return ans;
    38     }
    39     
    40     /** Returns whether the queue is empty. */
    41     bool empty() {
    42                 return s1.empty()&&s2.empty();
    43 
    44     }
    45     public:
    46         stack<int>s1;
    47         stack<int>s2;
    48 };
    49 
    50 /**
    51  * Your MyQueue object will be instantiated and called as such:
    52  * MyQueue* obj = new MyQueue();
    53  * obj->push(x);
    54  * int param_2 = obj->pop();
    55  * int param_3 = obj->peek();
    56  * bool param_4 = obj->empty();
    57  */
    View Code

    3 用队列实现栈

     思路:

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

     1 class MyStack {
     2 public:
     3     /** Initialize your data structure here. */
     4     MyStack() {
     5         
     6     }
     7     
     8     /** Push element x onto stack. */
     9     void push(int x) {
    10         q1.push(x);
    11     }
    12     
    13     /** Removes the element on top of the stack and returns that element. */
    14     int pop() {
    15         int size=q1.size()-1;
    16         for(size_t i=0;i<size;++i)
    17         {
    18             q1.push(q1.front());
    19             q1.pop();
    20         }
    21         int front=q1.front();
    22         q1.pop();
    23         return front;
    24     }
    25     
    26     /** Get the top element. */
    27     int top() {
    28         return q1.back();
    29     }
    30     
    31     /** Returns whether the stack is empty. */
    32     bool empty() {
    33         if(q1.empty())
    34         {
    35             return true;
    36         }else
    37             return false;
    38     }
    39     private:
    40         queue<int>q1;
    41 };
    42 
    43 /**
    44  * Your MyStack object will be instantiated and called as such:
    45  * MyStack* obj = new MyStack();
    46  * obj->push(x);
    47  * int param_2 = obj->pop();
    48  * int param_3 = obj->top();
    49  * bool param_4 = obj->empty();
    50  */
    View Code
  • 相关阅读:
    选择排序
    插入排序
    冒泡排序
    linux 常用命令全集
    Boost简介
    postgresql命令行
    Ncurses 命令行图形库
    rsync ssh文件同步
    BusyBox参考
    screen命令
  • 原文地址:https://www.cnblogs.com/lanjianhappy/p/11794145.html
Copyright © 2011-2022 走看看