https://leetcode.com/problems/count-substrings-that-differ-by-one-character/
虽然O(n^3)的解法很不优雅,很暴力,可是,能解决问题就行,这样的暴力解法,能想得出来么?

个人解答

  1. class Solution:
  2. def countSubstrings(self, s: str, t: str) -> int:
  3. res = 0
  4. for i in range(len(s)):
  5. for j in range(len(t)):
  6. diff = 0
  7. for k in range(min(len(s) - i, len(t) - j)):
  8. if s[k + i] != t[k + j]:
  9. diff += 1
  10. if diff > 1:
  11. break
  12. res += diff
  13. return res

参考:https://leetcode.com/problems/count-substrings-that-differ-by-one-character/discuss/917989/C%2B%2B-Brute-Force-4ms

题目分析

找到一个准则,而不是毫无头绪的解决,比如,本题中,两个str各自从某个位置出发开始扩展,就至少是一个合理的准则,算法本来就应该这样,按部就班,有规则。

其它解法

当然,这道题有更多更高效的解法,比如DP等等
但记录这道题的目的就是,说明如何踏踏实实,先用暴力的方法把题目做出来,再想着优化
其它解法可以参照discussion