Common Substring of two strings

Posted by Chander Shivdasani on Programmers See other posts from Programmers or by Chander Shivdasani
Published on 2013-10-19T06:37:15Z Indexed on 2013/10/19 10:13 UTC
Read the original article Hit count: 173

Filed under:
|
|
|

This particular interview-question stumped me:

Given two Strings S1 and S2. Find the longest Substring which is a Prefix of S1 and suffix of S2.

Through Google, I came across the following solution, but didnt quite understand what it was doing.

public String findLongestSubstring(String s1, String s2) {
        List<Integer> occurs = new ArrayList<>();
        for (int i = 0; i < s1.length(); i++) {
            if (s1.charAt(i) == s2.charAt(s2.length()-1)) {
                occurs.add(i);
            }
        }

        Collections.reverse(occurs);

        for(int index : occurs) {
            boolean equals = true;
            for(int i = index; i >= 0; i--) {
                if (s1.charAt(index-i) != s2.charAt(s2.length() - i - 1)) {
                    equals = false;
                    break;
                }
            }
            if(equals) {
                return s1.substring(0,index+1);
            }
        }

        return null;
    }

© Programmers or respective owner

Related posts about java

Related posts about algorithms