计算Java中两个字符串之间的重叠

时间:2016-04-20 21:54:06

标签: java arrays string optimization data-structures

我想编写一个函数,它将两个字符串作为输入并返回它们之间的重叠。例如:S1 =" ABCD"和S2 =" CDBA"函数应该返回overlap = 2,因为第一个字符串的后缀和第二个字符串的前缀类似于2个字符" CD"我写这段代码:

public class JavaStringArrayTests {
    public static void main(String[] args){
        JavaStringArrayTests jj= new JavaStringArrayTests();
        System.out.print(jj.overlap());
    }

    int overlap() {
        String f1 = "ABCD";
        String f2 = "DBCA";
        int max=0;
        char[] first= f1.toLowerCase().toCharArray();
        char[] second= f2.toLowerCase().toCharArray();

        for (int i=0; i<4; i++) {
            for (int i2=i; i2<4; i2++) {
                for (int j=0; j<4; j++) {
                    if (first[i]==second[j] )
                        max++;
                    else break;
                }
                if (max==0)
                    break;
            }
        }
        return max;
    }
}

此代码使用字符串而不重复,但是当我放置时例如:S1 =&#34; ATTC&#34;和S2 =&#34; TTCA&#34;它没有工作是否有任何想法来计算这个?感谢

2 个答案:

答案 0 :(得分:0)

不使用3 for循环使用2而是分别根据max和i分配和检查j的值。

注意:生成结果为&#34; 0&#34;如果两个字符串相等

for(int i=0; i<4; i++){
    for(int j=max; j<i; j++){
        if (first[i]==second[j] ){
            max++;
            break;
        }
        else
            break;
    }
}

答案 1 :(得分:-1)

您只需要两个滑动窗口进入数据字符串。通过调整窗口的宽度,可以确定重叠。

/**
 * @author aupanner
 */
public class Overlap {

    static int calculateOverlap(final String s1, final String s2) {
        final int s1len = s1.length();
        final int s2len = s2.length();
        final int maxlen = Integer.min(s1len, s2len);

        // from the longest overlap to the shortest possible.
        for (int len = maxlen; len > 0; len--) {
            // sliding window into s1 from 0
            for (int toffset = 0; toffset + len <= s1len; toffset++) {
                // sliding window into s2 from 0
                for (int ooffset = 0; ooffset + len <= s2len; ooffset++) {
                    //System.out.println("Comparing s1.regionMatches(" + toffset + ", s2, " + ooffset + ", " + len + ")");
                    if (s1.regionMatches(toffset, s2, ooffset, len)) {
                        return len;
                    }
                }
            }
        }

        // no overlap found.
        return 0;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        String s1 = "ABCD";
        String s2 = "DBCA";
        System.out.println("Maximum overlap is: " + calculateOverlap(s1, s2));
        String f1 = "ATTC";
        String f2 = "TTCA";
        System.out.println("Maximum overlap is: " + calculateOverlap(f1, f2));
    }
}