本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/41450987

通过本文你能学到如下知识:

(1)对数据结构中栈的理解,特别是Stack类中的peek()方法和pop()方法的区别。

(2)理解解题思路,提高思考问题的能力。

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.

题意:给定包含三种括号的字符串,判断该字符串中括号是否正确匹配。

解题思路:

(1)通过题意可知,括号是夹杂在字符之间的,而我们需要处理的是括号,所以,第一步是如何地将括号从字符串中分离出来。通过遍历字符串可将出现的括号存储起来。

(2)由于括号是成对进行匹配的,这里将成对出现的括号存储在HashMap中,以供后续查询比较。

(3)我们是通过一个栈来进行括号匹配的,我们将(1)中得到的括号往栈中存储以进行比较,第一个括号存储进去后,当第二个括号进入时需要进行判断。首先,判断其是否为

朝向左边的括号,这里用leftList.contains()进行判断,如果是不朝向左边的括号,将该括号压入栈中;如果不是朝向左边的括号,就需要从栈中取出元素和该括号进行比较,这里

用peep()方法获取当前的栈顶元素(不移除该元素)。其次,通过(2)中已获取的Map来得到与当前括号匹配的括号,如果得到的括号正好匹配,则从当前栈中移除已有元素,移

除栈顶元素的方法为pop();如果得到的括号不匹配,则匹配失败,返回false。最后,依次类推,直到所有的括号都进行匹配判断为为止。

PS:上面的解题思路肯定不是最好的,但其是本人自己思考的结果,虽然代码很罗嗦,但是思路还是比较清晰的,希望对你有所帮助,同时希望你给出建议,也希望能和大神进行一些交流。

解题代码如下(PS:本人技术比较菜,写的代码也很菜,但是OJ还是完全可以通过,大家有比较好的思路希望能够分享,谢谢):

public boolean isValid(String s) {
        int len = s.length();
		boolean isvalid = true;
		Stack<Character> stack = new Stack<Character>();
		Character[] all = {'[','(','{',']',')','}'};
		Character[] left = {']',')','}'};
		List<Character> leftlist = Arrays.asList(left);
		List<Character> alllist = Arrays.asList(all);

		Map<Character, Character> map = new HashMap<Character, Character>();
		map.put('[', ']');
		map.put('(', ')');
		map.put('{', '}');
		map.put('}', '{');
		map.put(')', '(');
		map.put(']', '[');

		LinkedList<Character> linked = new LinkedList<Character>();
		for (int i = 0; i < len; i++) {
			if(alllist.contains(s.charAt(i))){
				linked.add(s.charAt(i));
			}
		}

		if(linked.size()==0) return  true;
		stack.push(linked.get(0));

		for (int i = 1; i < linked.size(); i++) {
			Character str = linked.get(i);
			if(leftlist.contains(str) && stack.size() > 0){
				if(map.get(str).equals(stack.peek())){
					stack.pop();
				}else{
					isvalid = false;
				}
			}else{
				stack.push(str);
			}
		}

		if(stack!=null && stack.size()>0){
			isvalid = false;
		}

		return isvalid;
    }

Leetcode_20_Valid Parentheses的更多相关文章

  1. [LeetCode] Remove Invalid Parentheses 移除非法括号

    Remove the minimum number of invalid parentheses in order to make the input string valid. Return all ...

  2. [LeetCode] Different Ways to Add Parentheses 添加括号的不同方式

    Given a string of numbers and operators, return all possible results from computing all the differen ...

  3. [LeetCode] Longest Valid Parentheses 最长有效括号

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  4. [LeetCode] Generate Parentheses 生成括号

    Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...

  5. [LeetCode] Valid Parentheses 验证括号

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

  6. LeetCode 22. Generate Parentheses

    Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...

  7. 【leetcode】Generate Parentheses

    题目简述: Given n pairs of parentheses, write a function to generate all combinations of well-formed par ...

  8. No.022:Generate Parentheses

    问题: Given n pairs of parentheses, write a function to generate all combinations of well-formed paren ...

  9. 【LeetCode】241. Different Ways to Add Parentheses

    Different Ways to Add Parentheses Given a string of numbers and operators, return all possible resul ...

随机推荐

  1. Kirill And The Game CodeForces - 842A

    CodeForces - 842A 需要将除法改换成乘法进行计算 #include<bits/stdc++.h> using namespace std; int main() { lon ...

  2. PHP $_GET 变量

    $_GET 变量 预定义的 $_GET 变量用于收集来自 method="get" 的表单中的值. 从带有 GET 方法的表单发送的信息,对任何人都是可见的(会显示在浏览器的地址栏 ...

  3. PHP MySQL 插入数据

    PHP MySQL 插入数据 使用 MySQLi 和 PDO 向 MySQL 插入数据 在创建完数据库和表后,我们可以向表中添加数据. 以下为一些语法规则: PHP 中 SQL 查询语句必须使用引号 ...

  4. PHP MySQL Update

    UPDATE 语句用于中修改数据库表中的数据. 更新数据库中的数据 UPDATE 语句用于更新数据库表中已存在的记录. 语法 UPDATE table_name SET column1=value, ...

  5. admin的配置

    当我们访问http://127.0.0.1:8080/admin/时,会出现: 执行命令: 生成同步数据库的脚本:python manage.py makemigrations             ...

  6. Git 处理tag和branch的命令

    最近想给GitHub 上的项目设置tag,可是使用GitHub Desktop,找了一圈都没找到快速设置Tag 的地方,最后只能通过终端命令来添加了. 想要查看Git 的命令,可以使用 git --h ...

  7. Java多线程的调度策略

    在Java多线程环境中,为保证所有线程的执行能按照一定的规则执行,JVM实现了一个线程调度器,它定义了线程调度的策略,对于CPU运算的分配都进行了规定,按照这些特定的机制为多个线程分配CPU的使用权. ...

  8. 求链表倒数第n个元素

    提示:设置一前一后两个指针,一个指针步长为1,另一个指针步长为n,当一个指针走到链表尾端时, 另一指针指向的元素即为链表倒数第n个元素. #include <stdio.h> #inclu ...

  9. FORM打开网页链接

     DECLARE l_server_url VARCHAR2(100); l_parameters VARCHAR2(200); BEGIN fnd_profile.get('APPS_WEB_A ...

  10. Android 字体设置-Typeface讲解

    控件的字体设置的两种方式 常用的字体类型名称还有: Typeface.DEFAULT //常规字体类型 Typeface.DEFAULT_BOLD //黑体字体类型 Typeface.MONOSPAC ...