博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode - Valid Parentheses
阅读量:5152 次
发布时间:2019-06-13

本文共 2604 字,大约阅读时间需要 8 分钟。

2013.12.7 00:03

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

Solution:

  Matching parentheses can be well handled with a stack. Left brackets are pushed into the stack, while right brackets are popped together with the matching left brackets on the stack top. If a matching is impossible, the sequence is invalid.

  Time complexity is O(n), space complexity is O(n), where $n is the length of the sequence.

Accepted code:

1 // 1WA, 1AC 2 class Solution { 3 public: 4     bool isValid(string s) { 5         // IMPORTANT: Please reset any member data you declared, as 6         // the same Solution instance will be reused for each test case. 7         if(s == ""){ 8             return true; 9         }10         11         stack = new char[s.length()];12         if(stack == nullptr){13             return false;14         }15         16         bool ret;17         int i, len;18         19         pc = 0;20         len = s.length();21         ret = true;22         for(i = 0; i < len; ++i){23             switch(s[i]){24                 case '(':25                 case '[':26                 case '{
':27 stack[pc++] = s[i];28 break;29 case ')':30 if(pc <= 0 || stack[pc - 1] != '('){31 ret = false;32 }else{33 --pc;34 }35 break;36 case ']':37 if(pc <= 0 || stack[pc - 1] != '['){38 ret = false;39 }else{40 --pc;41 }42 break;43 case '}':44 if(pc <= 0 || stack[pc - 1] != '{
'){45 ret = false;46 }else{47 --pc;48 }49 break;50 default:51 ret = false;52 break;53 }54 if(!ret){55 break;56 }57 }58 // 1WA here, if stack is not empty, the sequence is invalid.59 if(pc != 0){60 ret = false;61 }62 63 delete[] stack;64 stack = nullptr;65 return ret;66 }67 private:68 char *stack;69 int pc;70 };

 

转载于:https://www.cnblogs.com/zhuli19901106/p/3462338.html

你可能感兴趣的文章
postgresql学习文档
查看>>
Struts2返回JSON数据的具体应用范例
查看>>
js深度克隆对象、数组
查看>>
socket阻塞与非阻塞,同步与异步
查看>>
团队工作第二天
查看>>
linux一些基本操作-防火墙操作
查看>>
System类
查看>>
tableView
查看>>
Happy Great BG-卡精度
查看>>
Xamarin Visual Studio不识别JDK路径
查看>>
菜鸟“抄程序”之道
查看>>
Ubuntu下关闭防火墙
查看>>
TCP/IP 邮件的原理
查看>>
w3m常用快捷键
查看>>
【Unity 3D】学习笔记四十一:关节
查看>>
原型设计工具
查看>>
windows下的C++ socket服务器(4)
查看>>
css3 2d转换3d转换以及动画的知识点汇总
查看>>
【Java】使用Eclipse进行远程调试,Linux下开启远程调试
查看>>
js对象属性方法
查看>>