码迷,mamicode.com
首页 > 其他好文 > 详细

Valid Parentheses

时间:2018-07-05 00:35:56      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:util   main   原理   字符串   code   标准   bool   parent   idp   


描述
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 package StacksAndqueues;
 2 
 3 import java.util.Stack;
 4 
 5 public class ValidParentheses {
 6 
 7     public static void main(String[] args) {
 8         // TODO Auto-generated method stub
 9         String s = "({})";
10         System.out.println(isValid(s));
11     }
12     // LeetCode, Valid Parentheses
13     // 时间复杂度 O(n),空间复杂度 O(n)
14 
15     public static boolean isValid(String s) {
16         String left = "([{";
17         String right = ")]}";
18         Stack<Character> stk = new Stack<Character>();
19         char[] ch = s.toCharArray();
20         for (char c : ch) {
21             if (left.contains(String.valueOf(c))) {
22                 stk.push(c);
23             } else {
24                 if (!stk.empty()) {
25                     if (right.indexOf(c) >= 0) {
26                         if (stk.peek() != left.charAt(right.indexOf(c)))  //查看栈顶
27                             return false;
28                         else
29                             stk.pop(); //利用栈的先进后出的原理
30                     } 
31                 }
32 
33             }
34         }
35         return stk.empty();
36     }
37 }
38 // 通过String.valueOf(char)函数把字符转化成字符串
39 // 举例
40 // char a=‘A‘;//定义一个字符a
41 // String str = String.valueOf(a);//把字符a转换成字符串str
42 
43 // string 和int之间的转换
44 //
45 // string转换成int :Integer.valueOf("12")
46 //
47 // int转换成string : String.valueOf(12)
48 //
49 //
50 //
51 // char和int之间的转换
52 //
53 // 首先将char转换成string
54 //
55 // String str=String.valueOf(‘2‘)
56 //
57 // Integer.valueof(str) 或者Integer.PaseInt(str)
58 //
59 // Integer.valueof返回的是Integer对象,Integer.paseInt返回的是int

Java Stack 类

栈是Vector的一个子类,它实现了一个标准的后进先出的栈。

堆栈只定义了默认构造函数,用来创建一个空栈。 堆栈除了包括由Vector定义的所有方法,也定义了自己的一些方法。

Stack()

除了由Vector定义的所有方法,自己也定义了一些方法:

 

序号方法描述
1 boolean empty() 
测试堆栈是否为空。
2 Object peek( )
查看堆栈顶部的对象,但不从堆栈中移除它。
3 Object pop( )
移除堆栈顶部的对象,并作为此函数的值返回该对象。
4 Object push(Object element)
把项压入堆栈顶部。
5 int search(Object element)
返回对象在堆栈中的位置,以 1 为基数。

Valid Parentheses

标签:util   main   原理   字符串   code   标准   bool   parent   idp   

原文地址:https://www.cnblogs.com/ncznx/p/9265965.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!