为什么必须在 if 语句中使用 [i + j] 和 j+1?

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

我正在尝试了解代码解决方案以查找字符串问题中首次出现的索引。我在网上找到了这段代码,但我完全可以理解这两个 ifs 语句行:
如果(针[j]!==干草堆[i + j])打破;
如果 (j + 1 === needle.length)
有人可以分解吗?

let strStr = (haystack, needle) => {
    // we loop through the first string 
    for (let i = 0; i < haystack.length; i++) {
        // we loop through the second string
        for (let j = 0; j < needle.length; j++) {
            if (needle[j] !== haystack[i + j]) break;
            if (j + 1 === needle.length) {
                return i
            }
        }
    }
    return -1
};
strStr('sadbutsad', 'sad')
javascript
1个回答
1
投票

所以这段代码实际上 doing 是查看字符串

haystack
并返回
needle
内的子字符串
haystack
开头的字符索引,如果有的话。

if (needle[j] !== haystack[i + j]) break;
在上下文中,
i
是 haystack 的子串的开头,当前正在测试它是否与 needle 相同。内部循环
j
正在检查 needle 和 haystack 的每个字符,看它们是否相同。 “needle”总是从零开始,因为你正在查看整个字符串,所以你使用
needle[j]
。 “haystack”因为有外循环所以从
i
开始,所以用了
haystack[i+j]
。如果这些字符不匹配,那么您的内循环就会知道它找到了与 needle 不同的东西,因此中断并继续进行外循环的下一次迭代。

if (j + 1 === needle.length) return i
更容易解释:如果 needle 是三个字符长,您只需要检查三个字符,并且由于它们都匹配(我们知道这是因为前面的条件没有
break
)那么我们知道我们已经大海捞针,可以返回初始索引

let strStr = (haystack, needle) => {
    // we loop through the first string 
    for (let i = 0; i < haystack.length; i++) {
        // we loop through the second string
        for (let j = 0; j < needle.length; j++) {
            // if the "j"th character of needle is not the same as the "j"th character of haystack starting at i:
            if (needle[j] !== haystack[i + j]) break;
            
            // have we run out of needle to test?
            if (j + 1 === needle.length) {
                return i
            }
        }
    }
    return -1
};
console.log(strStr('sadbutsad', 'sad'))

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