首页 > 代码库 > leetcode 20

leetcode 20

技术分享

判断括号的顺序是否正确;

思路:用一个堆栈来存储符号序列,按照符号匹配规则进行堆栈操作;

   前括号一律入栈,后括号如果跟栈顶符号匹配,栈顶符号出栈如果,若不匹配则返回false;

   最后栈为空返回true,否则返回false;

 

代码如下:

 1 class Solution { 2 public: 3     bool isValid(string s) { 4         int n = s.length(); 5         if(n%2 != 0) 6         { 7             return false; 8         } 9         vector<char> stack;10         if(s[0] != ( && s[0] != [ && s[0] != {)11         {12             return false;13         }14         else15         {16             stack.push_back(s[0]);17         }18         int j = 1;19         for(int i = 1; i < n; ++i)20         {21             if(s[i] == ( || s[i] == [ || s[i] == {)22             {23                 stack.push_back(s[i]);24             }25             else if(s[i] == ))26             {27                 if(stack.back() == ()28                 {29                     stack.pop_back();30                 }31                 else32                 {33                     return false;34                 }35             }36             else if(s[i] == ])37             {38                 if(stack.back() == [)39                 {40                     stack.pop_back();41                 }42                 else43                 {44                     return false;45                 }46             }47             else if(s[i] == })48             {49                 if(stack.back() == {)50                 {51                     stack.pop_back();52                 }53                 else54                 {55                     return false;56                 }57             }58         }59         if(stack.empty())60         {61             return true;62         }63         else64         {65             return false;66         }67     }68 };

 

leetcode 20