Count Substrings That Differ by One Character

给两个字符串s和t, 求有多少个s和t的子字符串差一个字符.

这题和数相同子串不同的就是数差一个字符的子串个数. 首先先数一下相同的子串个数, 然后再数不同的.

class Solution {
    public int countSubstrings(String s, String t) {
        int n = s.length();
        int m = t.length();
        int[][] allMatch = new int[n][m]; // # of substring all match for s and t untill i,j
        for(int i = 0; i < s.length(); i++) {
            for(int j = 0; j < t.length(); j++) {
                boolean ma = s.charAt(i) == t.charAt(j);
                if(i == 0 || j == 0){
                    if(ma){
                        allMatch[i][j] = 1;
                    }
                }
                else
                {
                    if(ma){
                        allMatch[i][j] = allMatch[i - 1][j - 1] + 1;
                    }
                    else{
                        allMatch[i][j] = 0;
                    }
                }
            }
        }
        int[][] missOne = new int[n][m];
        int res = 0;
        for(int i = 0; i < s.length(); i++) {
            for(int j = 0; j < t.length(); j++) {
                boolean ma = s.charAt(i) == t.charAt(j);
                if(i == 0 || j == 0){
                    if(!ma){
                        missOne[i][j] = 1;
                    }
                }
                else
                {
                    if(ma){
                        missOne[i][j] = missOne[i - 1][j - 1];
                    }
                    else{
                        missOne[i][j] = allMatch[i - 1][j - 1] + 1;
                    }
                }
                res += missOne[i][j];
            }
        }
        return res;
    }
}