我在在线编辑器上测试了我的代码,它在我测试的所有示例中都运行良好,但是当我将它提交到 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"))
问题是您依赖于
readedIndices
数组的全局状态。但是 isAnagram
函数可能会在程序的同一次运行期间使用 distinct 输入多次调用。解决此问题的一种方法是在 readedIndices
(顶部)内同时定义 checkReadedIndices
和 isAnagram
。