LeetCode 的 Valid Anagram 挑战并没有通过所有测试用例,但它在我的编辑器中运行良好,为什么?

问题描述 投票:0回答:1

我在在线编辑器上测试了我的代码,它在我测试的所有示例中都运行良好,但是当我将它提交到 LeetCode 时它失败了。为什么?

LeetCode submission result:

Wrong Answer 
24 / 38 testcases passed
Input
s = "a"
t = "a"
Output: false
Expected: true

Leetcode 的结果显示我的代码返回了“false”,但是如果我在我的编辑器上运行相同的例子,它会正确地返回“true”

我的代码:

/**
 * @param {string} s
 * @param {string} t
 * @return {boolean}
 */

let readedIndices = []
function checkReadedIndices(indice){
    let res = false
    for(let i=0; i<readedIndices.length; i++){
        if(indice == readedIndices[i]){
            res = true
        }
    }
    return res
}

var isAnagram = function(s, t) {
    let result = false
    if(s.length !== t.length)
        return result
    for(let i=0; i < s.length; i++){
        for(let n=0; n < t.length; n++){
            if(s[i] === t[n]){
                if(checkReadedIndices(n) === false){
                    readedIndices.push(n)
                    break
                }
            }
        }
    }
    if(readedIndices.length === s.length)
        result = true

    return result
};
//console.log(isAnagram("a", "a"))
javascript anagram
1个回答
0
投票

问题是您依赖于

readedIndices
数组的全局状态。但是
isAnagram
函数可能会在程序的同一次运行期间使用 distinct 输入多次调用。解决此问题的一种方法是在
readedIndices
(顶部)内同时定义
checkReadedIndices
isAnagram

© www.soinside.com 2019 - 2024. All rights reserved.