[Codility] (Lesson7 | Stacks and Queues) Brackets - JavaScript


質問する
A string S consisting of N characters is considered to be properly nested if any of the following conditions is true:
S is empty;
S has the form "(U)"or "[U]"or "{U}"where U is a properly nested string;
S has the form "VW"where V and W are properly nested strings.
For example, the string "{[()()]}"is properly nested but "([)()]"is not.
Write a function:
function solution(S);
that, given a string S consisting of N characters, returns 1 if S is properly nested and 0 otherwise.
For example, given S = "{[()()]}", the function should return 1 and given S = "([)()]", the function should return 0, as explained above.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [0..200,000];
string S consists only of the following characters: "(", "{", "[", "]", "}"and/or ")".
もんだいぶんせき
stack問題では、各文字列に括弧が付いた文字列が与えられます.文字列が本物かどうかの確認には3つのケースがあります.
1つ目は、空の文字列の場合
2つ目は、「()」、「[]」、「{}」などです.
3つ目のケースは、「{()[]}」のように、複数のオーバーラップがありますが、オーバーラップは適切です.
「[{}(])」を返すと、開いている括弧に対応する閉じた括弧はありません.
もし本当ならば、1が偽物ならば、0を返します.
問題を解く
文字列が付与されたデータは配列形式になり、最初の文字列から順にナビゲートされます.左かっこの場合はstackとして保存する配列にプッシュし、閉じる場合はプッシュした配列の最後に一致するかっこがあることを確認してポップアップします.適切なカッコがある場合、スタック内の配列は空の配列になります.そうでなければ、0を正しく指定されていない文字列に戻すだけです.
コード#コード#
function solution(S) {
    // write your code in JavaScript (Node.js 8.9.4)
    if(S.length === 0) return 1

    let str = S.split('');
    let stack = [];
    for(let i = 0; i<str.length; i++){
        if(str[i]==='(' || str[i]==='[' || str[i]==='{') stack.push(str[i])
        else {
            if(stack.length===0) return 0    
            if(str[i]===')' && stack[stack.length-1]==='(') stack.pop()
            if(str[i]===']' && stack[stack.length-1]==='[') stack.pop()
            if(str[i]==='}' && stack[stack.length-1]==='{') stack.pop()
        }
    }
    return stack.length > 0 ? 0 : 1
}
最終プロセス

ソース
https://app.codility.com/programmers/lessons/7-stacks_and_queues/