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

    题目需要我们判断是否是正确的括号使用,这道题有点类似镜像串。用一个pos变量记录每次是否是对应的()[]{},如果符合则减一,如果不符合就把pos变量一直加上去直到碰到符合的括号,最后如果能削减到0说明括号的使用正确,不能则说明不正确。

     1 bool isValid(char* s) {
     2     int pos = 0;//记录还没排除的括号
     3     for(int i=0;s[i]!='';i++) {
     4         /*()的ASCII码差一,[]{}差二,所以在if第二个判断条件要加上一,不然()正确使用不通过,而[]{}最后就算加一整型取整了依旧等一*/
     5         if(pos && (s[i]-s[pos-1]+1)/2 == 1){
     6             pos--;
     7         }else {
     8             s[pos++] = s[i];
     9         }
    10     }
    11     return pos ? false : true;
    12 }

  • 相关阅读:
    运算符优先级
    Tips—查询某结构体
    在线词典--(一、流程分析)
    数据库—SQLite3
    回调函数(转载)
    UNIX域套接字
    进程间通信小结
    HDU_oj_2027 统计元音
    HDU_oj_2026 首字母变大写
    HDU_oj_2025 查找最大字母
  • 原文地址:https://www.cnblogs.com/real1587/p/9993821.html
Copyright © 2011-2022 走看看