Java 3ms | easy to understand code
\n\nSince the substring need to have one and only one different character, we start with finding differenct characters in String s and String t. Then, we work b
![image](https://assets.leetcode.com/users/images/d5770b43-da09-4849-9398-3ecb5945ae19_1604182467.9118745.png)\n\nSince the substring need to have one and only one different character, we start with finding differenct characters in String s and String t. Then, we work both backward and forward to find longest matching distance: left and right. In this example, we can choose 0 to 3 characters from left, that has 4 choice. We can also choose 0 to 4 characters from right, that has 5 choice. The total combination with only 1 different character produced by characters in position i and j is (left+1) * (right + 1) = 4 * 5 = 20. Sum all the combination at different i and j would give us result.\n\n```\npublic int countSubstrings(String s, String t) {\n\tchar[] cs = s.toCharArray();\n\tchar[] ct = t.toCharArray();\n\n\tint total = 0;\n\tfor (int i = 0 ; i < cs.length; ++i) {\n\t\tfor (int j = 0 ; j < ct.length ; ++j) {\n\n\t\t\tif (cs[i] == ct[j]) continue;\n\n\t\t\tint left = 0;\n\t\t\tint x = i-1, y = j-1;\n\t\t\twhile(x >= 0 && y >= 0) {\n\t\t\t\tif (cs[x--] == ct[y--])\n\t\t\t\t\t++left;\n\t\t\t\telse\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tint right = 0;\n\t\t\tx = i+1;\n\t\t\ty = j+1;\n\t\t\twhile(x < cs.length && y < ct.length) {\n\t\t\t\tif (cs[x++] == ct[y++])\n\t\t\t\t\t++right;\n\t\t\t\telse\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\ttotal += (left + 1) * (right + 1);\n\t\t}\n\t}\n\treturn total;\n}\n```\n\n\n
['Java']