1638. Count Substrings That Differ by One Character

Given two strings s and t, find the number of ways you can choose a non-empty substring of s and replace a single character by a different character such that the resulting substring is a substring of t. In other words, find the number of substrings in s that differ from some substring in t by exactly one character.

We just need to compare the substring of t and s and see if the difference is 1.

We can set up two pointers, both pointing to the same index of s and t. While the pointers move forward, we would accumulate the difference, if the difference is larger than one, which cannot be counted, we would break the loop.

We would try to use the above method for all the indexes of s and t.

class Solution {
public:
    int countSubstrings(string s, string t) {
        int ans = 0;
        for(int i = 0; i < t.size(); i++){
            for(int j = 0; j < s.size(); j++){
                int x = i;
                int y = j;
                int diff = 0;
                while(x < t.size() && y < s.size()){
                    if(t[x] != s[y])diff++;
                    if(diff == 1)ans++;
                    if(diff == 2)break;
                    x++;
                    y++;
                }
            }
        }
        return ans;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
>