String search string (hand tear BF algorithm, teacher Wang Zhuo, Qingdao University version)

       This is something I wrote a long time ago. At that time, I felt it when I watched the data structure video of Mr. Wang Zhuo, so I wrote it again. get down to business

 

Implemented function: find a string in a string

Application scenario: Find virus gene chains in biological gene chains

upper code

            // 面试题: 在str1 里面查找 str2 的位置,并以一个数组的形式输出 出来
            // 答案 :[1, 5, 12, 19]
        var str1 = 'ssjhgsjhffdgsjhdfsfsjh'
        var str2 = 'sjh'

        // bf算法穷举
        function bf(s, t) {
            let i = 0
            let j = 0
            var arr = []
            // debugger
            while (i <= s.length && j <= t.length) {
                if (s[i] == t[j]) {
                    i++
                    j++
                    if (j > t.length - 1) {
                        arr.push(i - t.length)
                        if (i >= s.length - t.length + 1) {
                            return arr
                        }
                    }
                } else {
                    i = i - j + 1
                    j = 0
                    if (i >= s.length - 1) {
                        return arr
                    }
                }
            }
        }
        console.log(bf(str1, str2));
        // indexOf 就是上面的语法糖
        // console.log(str1.indexOf(str2));
 

It is also possible to use recursion to improve the algorithm

It’s just that it needs to be dealt with when replacing it. I just wrote 123 as a placeholder. If the amount of data is relatively large, it is recommended to use symbol data instead

       // 可以用递归 
        let arrIndex = []
        function index(str1,str2){
            if(str1.indexOf(str2)!==-1){
                arrIndex.push(str1.indexOf(str2))
                str1 = str1.replace(str2,'123')
                index(str1,str2)
            }
            return arrIndex
        }
        console.log(index(str1,str2));

Big brothers and sisters are welcome to give a like, leave a message in the comment area to discuss!

Guess you like

Origin blog.csdn.net/fightingLKP/article/details/126249546