Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Teddy Zugana
Teddy Zugana

Posted on

     

Java, Common substring of two string in JAVA

public String getLongestCommonSubstring(String str1, String str2){            int m = str1.length();            int n = str2.length();            int max = 0;            int[][] dp = new int[m][n];            int endIndex=-1;            for(int i=0; i<m; i++){                for(int j=0; j<n; j++){                    if(str1.charAt(i) == str2.charAt(j)){                        // If first row or column                        if(i==0 || j==0){                            dp[i][j]=1;                        }else{                            // Add 1 to the diagonal value                            dp[i][j] = dp[i-1][j-1]+1;                        }                        if(max < dp[i][j])                        {                            max = dp[i][j];                            endIndex=i;                        }                    }                }            }            // We want String upto endIndex, we are using endIndex+1 in substring.            return str1.substring(endIndex-max+1,endIndex+1);        }    }
Enter fullscreen modeExit fullscreen mode

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

vi veri veniversum vivus vici Noob Teams
  • Location
    Indonesia Jakarta
  • Education
    Computer Science Sriwijaya University
  • Work
    Programmer at Icon Plus, Ezeelink Jakarta
  • Joined

More fromTeddy Zugana

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp