アルゴリズム - 有効な括弧

Q:

入力文字列が有効な場合だけ文字を含む文字列を与えられた「(」「)」、「{」、「}」、「[」と「]」、決定します。

入力文字列が有効です:

  1. オープンブラケットは、ブラケットの同じ種類によって閉鎖されなければなりません。
  2. オープンブラケットが正しい順序で閉じなければなりません。

空の文字列も有効と見なされることに注意してください。

例1:

入力: "()" 
出力:

例2:

入力: "()[] {}" 
出力:

例3:

入力: "(]" 
出力:

例4:

入力: "([)]" 
出力:

例5:

入力: "{[]}" 
出力:

 

/ * * 
 * @param {文字列}だ
 * @return {ブール} 
 * / 
VARはisValid = 関数(S){
     VARの SL = s.length。
    一方(SL> 0 ){ 
        S = s.replace( '{}'、 '' 
        、S = s.replace( '[]'、 '' 
        、S = s.replace( '()'、 '' 

        SL - ; 
    } 
    
    戻り S == '' 
}。

 

付録:

正規表現についてのトリック:

    • 最も一般的なフラグ: 
      - i : case insensitive 
      - g : global (doesn't stop after first match)
      - m : multi-line
    • 最も一般的なアンカー: 
      - ^ : Start of string
      - $ : End of string
      - \A : Start of string (not affected by multi-line content)
      - \Z : End of string (not affected by multi-line content)
    • 最も一般的な数量: 
      - {n} : Exactly n times
      - {n,} : At least n times
      - {m,n} : Between m and n times
      - ? : Zero or one time
      - + : One or more times
      - * : Zero, one or more times
    • 最も一般的なメタシーケンス: 
      - . : Any character but \n and \r 
      - \w | \W : Any word character | Any non-word character
      - \d | \D : Any digit character | Any non-digit character
      - \s | \S : Any whitespace character | Any non-whitespace character
    • キャラクターセット : 
      — [abc] : Will match either a, b or c
      - [1-9] : Will match any digit from 1 to 9
      - [a-zA-Z] : Will match any letter
    • 任意の文字に一致しますが。 
      - [^abc] : Matches anything but a, b or c
    • エスケープ文字: 
      - \character (example : escaping + => \+)
    • (さらに見て、またグループを捕捉するために使用される)のグループを参照してください。 
      — (group of characters) (example : /(he)+/ will match 'hehehe'
    • 一つのグループまたは別: 
      - | : /^h((ello)|(ola))$/ will match both 'hello' and 'hola'

 

- 終わり -

 

「物理学者であることよりも硬く、面白い人、であるために。」 - リチャード・ファインマン

おすすめ

転載: www.cnblogs.com/bbcfive/p/11443881.html