zoukankan      html  css  js  c++  java
  • 平衡的括号问题

    平衡的括号 

      要运用栈的一些知识,STL。

    栈的特点是“先进后出”。

    头文件是<stack>,声明方式:"stack<int> s"。

    主要操作:

    push():把元素压入“栈顶”,又称入栈

    pop():从栈顶把元素弹出,出栈

    top():取栈顶元素(但不删除)

    size():测栈长(个数)

    empty():判断栈是否为空

    题目大意:

    输入一个包含“()”和“[]”的括号序列,判断是否合法。具体规则如下:

    (1)空串合法;(2)如果A和B都合法,则AB合法;(3)如果A合法则(A)和[A]都合法。

    题目分析:

    先要测出字符串的长度,如果串长==0,是合法的,输出Yes。接着判断第一个字符,如果是]和),也为no

    然后,就是在进行出入栈的操作了。

    其实,还可以判断字符长度,如果为奇数也输出no,经过基本的处理,效率会高一些

    代码部分:

     1 #include<cstdio> 
     2 #include<string>
     3 #include<iostream>
     4 #include<stack>
     5 using namespace std;
     6 string isOK(string str);
     7 
     8 /*
     9 *平衡括号问题,用栈解决
    10 *By hxiaohua 2016-11-03
    11 */
    12 int main()
    13 {
    14     string s;
    15     cin >> s;
    16     if (s.length() == 0)
    17         cout << "No
    ";
    18     else if (s[0] == ']' || s[0] == ')')
    19         cout << "No
    ";
    20     else
    21         cout << isOK(s)<<endl;
    22     return 0;
    23 }
    24 
    25 string isOK(string str)
    26 {
    27     stack<char> s0;
    28     for (int i = 0; i < str.length(); i++)
    29     {
    30         if (str[i] == '(' || str[i] == '[')
    31             s0.push(str[i]);
    32         else if (str[i] == ']')
    33         {
    34             if (s0.top() == '[')
    35                 s0.pop();
    36         }
    37         else
    38         {
    39             if (s0.top() == '(')
    40                 s0.pop();
    41         }
    42     }
    43     if(s0.empty())
    44         return "Yes";
    45     else
    46         return "No";
    47 }
  • 相关阅读:
    Java Web
    对象拷贝
    多线程
    容器
    新鲜出炉一份Java面试清单,共200+道题
    优秀博客
    【安防】自动光圈控制
    【硬件】变压器的电特性参数
    【工作总结】IPD开发管理流程
    【EMC】EMI滤波器
  • 原文地址:https://www.cnblogs.com/hxh88/p/6025755.html
Copyright © 2011-2022 走看看