2017-04-01 252 views
0

嘿所以我正在寫一個函數,檢查一系列大括號是否是一個有效的序列。我有下面的代碼,主要做我想要它做的,除了它總是返回false。如果我輸入一個有效的大括號序列,它會在正確的if語句中結束,但永遠不會返回true。我不明白爲什麼。返回函數if語句不執行

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

最後返回錯誤總是被從原始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

天啊。時間去睡覺,我想..謝謝! –