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 }
  • 相关阅读:
    eclipse环境:把jdk1.6 改 jdk1.7或jdk1.8(改回也可以)(图文详解)
    SVN 将文件还原到之前的指定版本
    用起来很方便的枚举扩展类
    VS2015新功能
    EasyUi 动态列
    基于EasyUi的快速开发框架
    深圳某保险公司招聘职位列表
    考勤系统之计算工作小时数
    考勤系统之状态管理
    第一次裁员
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4099255.html
Copyright © 2011-2022 走看看