Description

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

Example

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

Challenge

O(n)的时间,n为括号的个数

解题:括号匹配问题,用栈来做较为简单,代码如下:

public class Solution {
/**
* @param s: A string
* @return: whether the string is a valid parentheses
*/
public boolean isValidParentheses(String s) {
// write your code here
Stack<Character>stack = new Stack<Character>();
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '['){
stack.push(s.charAt(i));
}else{ //pop前要先检查栈是不是空的
if(!stack.isEmpty()){
switch(s.charAt(i)){
case ')':
if(!stack.pop().equals('(')){
return false;
}
break;
case ']':
if(!stack.pop().equals('[')){
return false;
}
break;
case '}':
if(!stack.pop().equals('{')){
return false;
}
break;
}
}else{
return false;
}
}
}
if(stack.isEmpty()){
return true;
}else{
return false;
}
}
}

最新文章

  1. css随笔记
  2. Radmin Server-3.5 完美绿色破解版(x32 x64通用) 第三版 + 单文件制作方法
  3. python核心编程第六章练习6-14
  4. BZOJ3787 : Gty的文艺妹子序列
  5. Javascript计算中英文混输字符串长度V2
  6. viedeo
  7. Spring 使用外部部署文件
  8. Servlet程序开发--WEB开发模式(Mode I, Mode II)
  9. Singular value decomposition
  10. 1013. Battle Over Cities (25)
  11. PAT1081:Rational Sum
  12. Java选择排序,插入排序,快速排序
  13. Something of HTTP
  14. tchart5
  15. spring boot 的热部署插件
  16. python测试开发django-40.模型(model)中choices使用
  17. Java设计模式(1)工厂模式(Factory模式)
  18. c语言学习笔记---预编译
  19. 微服务—熔断器Hystrix
  20. JQuery传值,接收PrintWriter的int接收不了

热门文章

  1. Visual Studio 2017 安装过程问题解决
  2. eclipse安装activiti插件
  3. Mariadb相关
  4. vue-cli 项目安装失败 tunneling socket could not be established, cause=connect ECONNREFUSED
  5. redis应用场景:实现简单计数器-防止刷单
  6. nRF52832 BLE_DFU空中升级OTA(二)编译下载(SDK14.2.0)
  7. LSTM网络应用于DGA域名识别--文献翻译--更新中
  8. 数据结构与算法-图的最短路径Dijkstra
  9. 5.11-笨办法学python-习题13(argv)
  10. SET HANDLER - FOR