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

    Solution:

     1 public class Solution {
     2     public boolean isValid(String s) {
     3         if (s == null || s.length() == 0)
     4             return true;
     5         if (s.length() == 1)
     6             return false;
     7         int N = s.length();
     8         int i = 0;
     9         Stack<Character> myStack = new Stack<Character>();
    10         while (i < N) {
    11             char temp = s.charAt(i);
    12             if (temp == '(' || temp == '{' || temp == '[') {
    13                 myStack.push(temp);
    14                 i++;
    15             } else {
    16                 if (!myStack.isEmpty()) {
    17                     char t = myStack.pop();
    18                     if (((t == '(') && (temp == ')'))
    19                             || ((t == '{') && (temp == '}'))
    20                             || ((t == '[') && (temp == ']'))) {
    21                         i++;
    22                     } else {
    23                         return false;
    24                     }
    25                 } else {
    26                         return false;
    27                 }
    28             }
    29         }
    30         if(myStack.isEmpty())
    31             return true;
    32         else
    33             return false;
    34     }
    35 }

    我的代码风格太差了,贴一下大神的代码:

     1 public class Solution {
     2     public boolean isValid(String s) {
     3         if (s == null)
     4             return false;
     5         Stack st = new Stack();
     6         for (int i = 0; i < s.length(); i++) {
     7             if(s.charAt(i)==']'||s.charAt(i)==')'||s.charAt(i)=='}'){
     8                 if(st.empty())
     9                     return false;
    10                 else{
    11                     char c= st.pop().toString().charAt(0);
    12                     if(!((c=='('&&s.charAt(i)==')')||(c=='['&&s.charAt(i)==']')||(c=='{'&&s.charAt(i)=='}'))){
    13                         return false;
    14                     }                
    15                 }
    16             }else{
    17                 st.push(s.charAt(i));
    18             }
    19         }
    20         return st.empty();
    21     }
    22 }
  • 相关阅读:
    C++ Sqlite3的基本使用
    DirectX11 初探XMVECOTR&XMMATRIX
    lib和dll文件的初了解
    游戏设计模式——C++单例类
    C++11智能指针的深度理解
    你的文章里为什么不放源码Github链接了
    堡垒机的核心武器:WebSSH录像实现
    Asciinema文章勘误及Web端使用介绍
    Asciinema:你的所有操作都将被录制
    Django实现WebSSH操作物理机或虚拟机
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4099255.html
Copyright © 2011-2022 走看看