2017-04-01 8 views
0

ちょっと、一連の中カッコが有効なシーケンスかどうかをチェックする関数を書いています。私は次のコードを持っています。それは、常にfalseを返すことを除いて、私がやりたいことを大部分は行います。有効な中カッコのシーケンスを入力すると、正しいif-statementで終わりますが、決してtrueを返しません。なぜか分からない。ifステートメント内でreturn関数が実行されない

function match(s) { 
 
    if (s === '(') { 
 
    return ')' 
 
    } 
 
    else if (s === '[') { 
 
    return ']' 
 
    } 
 
    else if (s === '{') { 
 
    return '}' 
 
    } 
 
} 
 

 
function open(b) { 
 
    if ((b === '(') || (b === '[') || (b === '{')) { 
 
    return true; 
 
    } 
 
    return false; 
 
} 
 

 
function checkValid(string, temp, n) { 
 
    var current = string.charAt(n) 
 
    var currentMatch = temp.charAt(0) 
 

 
    if (!(current) && (n === string.length) && (temp === "")) { 
 
    console.log('hey') 
 
    return true 
 
    } 
 

 
    if (open(current)) { 
 
    temp = match(current).concat(temp) 
 
    checkValid(string, temp, n+1) 
 
    } 
 
    else { 
 
    if (current === currentMatch) { 
 
     temp = temp.substr(1) 
 
     checkValid(string, temp, n+1) 
 
    } 
 
    return false; 
 
    } 
 
    return false; 
 
} 
 

 
function validBraces(braces) { 
 
    var n = 0 
 
    var temp = '' 
 
    return checkValid(braces, temp, n) 
 
} 
 

 
validBraces('()') // should return true 
 
validBraces('[[)}}{') //should return false

答えて

0

最後のリターンfalseが常にあなたの元checkValid関数呼び出しから返されています。

これは、再帰的なcheckValid呼び出しを返さないためです。

function match(s) { 
    if (s === '(') { 
    return ')' 
    } 
    else if (s === '[') { 
    return ']' 
    } 
    else if (s === '{') { 
    return '}' 
    } 
} 

function open(b) { 
    if ((b === '(') || (b === '[') || (b === '{')) { 
    return true; 
    } 
    return false; 
} 

function checkValid(string, temp, n) { 
    var current = string.charAt(n) 
    var currentMatch = temp.charAt(0) 

    if (!(current) && (n === string.length) && (temp === "")) { 
    console.log('hey') 
    return true 
    } 

    if (open(current)) { 
    temp = match(current).concat(temp) 
    return checkValid(string, temp, n+1) 
    } 
    else { 
    if (current === currentMatch) { 
     temp = temp.substr(1) 
     return checkValid(string, temp, n+1) 
    } 
    return false; 
    } 
    return false; 
} 

function validBraces(braces) { 
    var n = 0 
    var temp = '' 
    return checkValid(braces, temp, n) 
} 

validBraces('()') // should return true 
validBraces('[[)}}{') //should return false 
+0

ジー達人。寝る時間があると思います..ありがとう! –

関連する問題