zoukankan      html  css  js  c++  java
  • 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.

    第一遍:

     1 public class Solution {
     2     public boolean isValid(String s) {
     3         // Note: The Solution object is instantiated only once and is reused by each test case.
     4         // '(' - '0' :: -8
     5         // ')' - '0' :: -7
     6         
     7         // '[' - '0' :: 43
     8         // ']' - '0' :: 45
     9         
    10         // '{' - '0' :: 75
    11         // '}' - '0' :: 77
    12         Stack<Integer> st = new Stack<Integer>();
    13         for(int i = 0; i < s.length(); i ++){
    14             int c = s.charAt(i) - '0';
    15             if(c == -8 || c == 43 || c == 75) st.push(c);
    16             else if(c == -7){
    17                 if(st.size() != 0 && st.peek() == -8)st.pop();
    18                 else return false;
    19             }
    20             else if(c == 45){
    21                 if(st.size() != 0 && st.peek() == 43)st.pop();
    22                 else return false;
    23             }
    24             else if(c == 77){
    25                 if(st.size() != 0 && st.peek() == 75)st.pop();
    26                 else return false;
    27             }
    28             else return false;
    29         }
    30         if(st.size() != 0) return false;
    31         return true;
    32     }
    33 }

    第三遍:

     1 public class Solution {
     2     public boolean isValid(String s) {
     3         LinkedList<Character> ll = new LinkedList<Character>();
     4         if(s == null || s.length() == 0) return false;
     5         for(int i = 0; i < s.length(); i ++){
     6             if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') ll.push(s.charAt(i));
     7             else if(ll.size() == 0 || (s.charAt(i) == ')' && ll.peek() != '(') ||
     8             (s.charAt(i) == ']' && ll.peek() != '[') || (s.charAt(i) == '}' && ll.peek() != '{')) return false;
     9             else ll.pop();
    10         }
    11         return ll.size() == 0;
    12     }
    13 }
  • 相关阅读:
    词汇表处理脚本
    jLowNote又,我为什么要说又,有bug
    于是按照贴吧某同学的指教,把imageViewer里那个愚蠢的语句改了
    捉到Bug一只,jLowNote里的
    高产赛母猪
    我超喜欢Nimbus风格的!
    专注写记事本三十年
    秒秒钟食言
    别再打了,Java和Python,你们其实都是C
    电话本写完了,发个1.0吧
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3893984.html
Copyright © 2011-2022 走看看