由Java实现Valid Parentheses

  一、题目

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

  An input string is valid if:

  Open brackets must be closed by the same type of brackets.

  Open brackets must be closed in the correct order.

  Note that an empty string is also considered valid.

  Example 1:

  Input: "()"

  Output: true

  Example 2:

  Input: "()[]{}"

  Output: true

  Example 3:

  Input: "(]"

  Output: false

  Example 4:

  Input: "([)]"

  Output: false

  Example 5:

  Input: "{[]}"

  Output: true

  二、解题思路

  1、利用List集合实现一个栈;

  2、将字符串s转换成字符数组,并循环遍历;

  3、如果字符为:"{、(、["中的一个,则存入集合中;

  4、如果字符为:"}、)、]"中的一个,则取出集合中最后一个元素进行比较;

  5、如能匹配上,则删除集合中最后一个元素,否则返回false;

  6、最后判断集合大小是否为0,如是则返回true。

  三、代码实现

  public boolean isValid(String s) {

  if ("".equals(s)) {

  return true;

  } else {

  Map parentheseMap = new HashMap();

  parentheseMap.put(')', '(');

  parentheseMap.put(']', '[');

  parentheseMap.put('}', '{');

  char[] sArr = s.toCharArray();

  List stackList = new ArrayList();

  for (int i = 0; i < sArr.length; i++) {

  if (sArr[i] == '(' || sArr[i] == '[' || sArr[i] == '{') {

  stackList.add(sArr[i]);

  } else {无锡人流多少钱 http://wapyyk.39.net/wx/zonghe/fc96e.html

  if (stackList.size() == 0) {

  return false;

  } else {

  char temp = stackList.get(stackList.size() - 1);

  if (temp == parentheseMap.get(sArr[i])) {

  stackList.remove(stackList.size() - 1);

  } else {

  return false;

  }

  }

  return stackList.size() == 0 ? true : false;

  }

  }

转载于:https://www.cnblogs.com/djw12333/p/10958726.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值