Home > Web Front-end > JS Tutorial > body text

Use JavaScript to find the largest identical substring of two strings (code example)

云罗郡主
Release: 2018-10-17 16:50:21
forward
3414 people have browsed it

The content of this article is about using JavaScript to find the largest identical substring of two strings (code example). It has certain reference value. Friends in need can refer to it. I hope it will be useful to you. helped.

Ideas:

1. Find the largest and smallest string of two strings (according to length).
2. From the smallest string, first take the substring of the length of the string, determine whether the larger string contains the substring, if not, reduce the length by 1, and take the substring of the length from the small string. Then judge again, and so on.

<script>
function getMaxStr(str1,str2){
    var max = str1.length > str2.length ? str1 : str2;
    var min = (max == str1 ? str2 : str1);
    for(var i = 0; i < min.length; i++){
        for(var x = 0, y = min.length - i;y != min.length + 1;x++,y++){
        //y表示所取字符串的长度
            var newStr = min.substring(x,y);
            //判断max中是否包含newStr
            if(max.indexOf(newStr) != -1){
                return newStr;
            }
        }
    }
    return -1;
}
alert(getMaxStr("abc","abcd"));//abc
</script>
Copy after login

The above is the complete introduction to PHP. If you want to know more about JavaScript video tutorial, please pay attention to the PHP Chinese website.

The above is the detailed content of Use JavaScript to find the largest identical substring of two strings (code example). For more information, please follow other related articles on the PHP Chinese website!

source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template