【JAVA、C++】LeetCode 020 Valid Parentheses
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.
解题思路:
由于"()","[()]","{{({[]})}}"都会通过,即出现')]}'这种字符就需要判断前面字符是否是对应的字符,如果用指针的话,实现起来相当复杂,考虑到这种情况和栈的后进先出颇为相似,因此采用stack类
JAVA实现如下:
	static public boolean isValid(String s) {
        Stack<Integer> stack = new Stack<Integer>();
        for (int i = 0; i < s.length(); i++) {
            int pos = "()[]{}".indexOf(s.charAt(i));
            if (pos % 2 !=0) {
                if (stack.isEmpty() || stack.pop() != pos - 1)
                    return false;
            } else
            	stack.push(pos);
        }
        return stack.isEmpty();
    }
C++
  class Solution {
  public:
      bool isValid(string s) {
          stack<char> stk;
          for (int i = ; i < s.length(); i++) {
              if (s[i] == '(' || s[i] == '[' || s[i] == '{')
                  stk.push(s[i]);
              else {
                  if (stk.empty())
                      return false;
                  if (stk.top() == '(' && s[i] == ')')
                      stk.pop();
                  else if (stk.top() == '[' && s[i] == ']')
                      stk.pop();
                  else if (stk.top() == '{' && s[i] == '}')
                      stk.pop();
                  else
                      return false;
              }
          }
          return stk.empty();
      }
  };
【JAVA、C++】LeetCode 020 Valid Parentheses的更多相关文章
- 【JAVA、C++】LeetCode 022 Generate Parentheses
		
Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...
 - 【JAVA、C++】LeetCode 005 Longest Palindromic Substring
		
Given a string S, find the longest palindromic substring in S. You may assume that the maximum lengt ...
 - 【JAVA、C++】LeetCode 002 Add Two Numbers
		
You are given two linked lists representing two non-negative numbers. The digits are stored in rever ...
 - 【JAVA、C++】LeetCode 019 Remove Nth Node From End of List
		
Given a linked list, remove the nth node from the end of list and return its head. For example, Give ...
 - 【JAVA、C++】LeetCode 010 Regular Expression Matching
		
Implement regular expression matching with support for '.' and '*'. '.' Matches any single character ...
 - 【JAVA、C++】 LeetCode 008 String to Integer (atoi)
		
Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. ...
 - 【JAVA、C++】LeetCode 007 Reverse Integer
		
Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 解题思路:将数字 ...
 - 【JAVA、C++】LeetCode 006 ZigZag Conversion
		
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like ...
 - 【JAVA、C++】LeetCode 004 Median of Two Sorted Arrays
		
There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two ...
 
随机推荐
- list 内部方法
			
代码 #list内部方法 l=['a','9','c','a','3','7'] print(dir(l)) l.append('v') print(l)#append(self, p_object) ...
 - BZOJ2818        欧拉函数
			
题意:求1--n中满足gcd(x,y)的值为质数的数对(x,y)的数目 ( (x,y)和(y,x)算两个 ) sol: 设p[i]是一个质数,那么以下两个命题是等价的: 1.gcd(x,y)=1 2. ...
 - USACO 3.3   fence       欧拉回路
			
题意:求给定图的欧拉回路(每条边只走一次) 若欧拉回路存在,图中只可能有0个or2个奇数度的点. 求解时,若有奇数度的点,则必须从该点开始.否则可以从任一点开始 求解过程:dfs //主程序部分 # ...
 - POJ 3258 River Hopscotch
			
River Hopscotch Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 11031 Accepted: 4737 ...
 - 浅议SNMP安全、SNMP协议、网络管理学习
			
相关学习资料 tcp-ip详解卷1:协议.pdf(重点看25章SNMP部分) http://www.rfc-editor.org/rfc/rfc1213.txt http://www.rfc-edit ...
 - What to call your Academic Event
 - 字符串匹配的KMP算法详解及C#实现
			
字符串匹配是计算机的基本任务之一. 举例来说,有一个字符串"BBC ABCDAB ABCDABCDABDE",我想知道,里面是否包含另一个字符串"ABCDABD" ...
 - hibernate的pojo和xml文件
 - Linux内核中的fastcall和asmlinkage宏
			
代码中看见:#define _fastcall 所以了解下fastcall -------------------------------------------------------------- ...
 - UVALive 6125 I’ve Got Your Back(gammon) 题解
			
http://vjudge.net/problem/viewProblem.action?id=37481 East Central Regional Contest Problem D: I’ve ...