zoukankan      html  css  js  c++  java
  • 20. Valid Parentheses

    Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

    An input string is valid if:

    1. Open brackets must be closed by the same type of brackets.
    2. Open brackets must be closed in the correct order.

    Note that an empty string is also considered valid.

    Example 1:

    Input: "()"
    Output: true
    

    Example 2:

    Input: "()[]{}"
    Output: true
    

    Example 3:

    Input: "(]"
    Output: false
    

    Example 4:

    Input: "([)]"
    Output: false
    

    Example 5:

    Input: "{[]}"
    Output: true
    
     1 class Solution {
     2     public char map(char c) {
     3         if (c == ')') return '(';
     4         if (c == ']') return '[';
     5         if (c == '}') return '{';
     6         return ' ';
     7     }
     8     public boolean isValid(String s) {
     9         int n = s.length();
    10         Map<String, String> map = new HashMap<>();
    11         
    12         if (n == 0) return true;
    13         char []stack = new char[n];
    14         int k = 0;
    15         for (int i = 0; i < n; ++i) {
    16             char c = s.charAt(i);
    17             if (c == '(' || c == '[' || c == '{') {
    18                 stack[k++] = c;
    19             } else {
    20                 if (k == 0 || stack[--k] != map(c)) {
    21                     return false;
    22                 }
    23             }
    24         }
    25         if (k== 0)
    26             return true;
    27         else 
    28             return false;
    29     }
    30 }
  • 相关阅读:
    Python基础知识大总结
    Python基础教程第一章 python基础知识
    XDUOJ 1000-1002题解
    C# PDF格式 下载
    C# 文件(图片)下载
    C# DataTable转List
    C# Excel导入与导出
    C# 文件压缩与解压
    C# 文件流 导入 导出
    C# lambda表达式
  • 原文地址:https://www.cnblogs.com/hyxsolitude/p/12304889.html
Copyright © 2011-2022 走看看