• 2018美团笔试字符串问题


    字符串距离

    题目:

    给出两个相同长度的由字符 a 和 b 构成的字符串,定义它们的距离为对应位置不同的字符的数量。如串”aab”与串”aba”的距离为 2;串”ba”与串”aa”的距离为 1;串”baa”和串”baa”的距离为 0。下面给出两个字符串 S 与 T,其中 S 的长度不小于 T 的长度。我们用|S|代表 S 的长度,|T|代表 T 的长度,那么在 S 中一共有|S|-|T|+1 个与T长度相同的子串,现在你需要计算 T 串与这些|S|-|T|+1 个子串的距离的和。

    输入描述:

    第一行包含一个字符串 S。第二行包含一个字符串 TS 和 T 均由字符 a 和 b 组成,1 ≤ |T| ≤ |S| ≤105 。

    输出描述:

    输出对应的答案。

    样例:

    in:
    aab
    aba
    out:
    2
    
    in:
    aaabb
    bab
    out:
    5

    题解:

    如果这个题死盯着字串弄是没有思路的,但是如果你盯着T中的每一个字符看,就有思路了 ;

    对于T中的每一个字符,看清楚它会和S中的哪些字母去比较,然后计算一下每一个字符对答案的贡献就行了,看下图:

    这里写图片描述

    T中0位置的字符和S中橙色的字符比较,……看图应该就明白了。

    时间复杂度:O(n)O(n)

    这题题中给出了只有ab两种字母,那有其他字母该怎么搞呢,其实一样的,只不过把代码中的ab变量用一个长度为26的数组代替就好了。具体的看看代码。 

    #include<algorithm>
    #include<bitset>
    #include<cmath>
    #include<cstdio>
    #include<cstdlib>
    #include<cstring>
    #include<iostream>
    #include<map>
    #include<queue>
    #include<set>
    #include<stack>
    #include<string>
    #include<vector>
    using namespace std;
    #defineis_lower(c) (c >='a'&& c <='z')
    #defineis_upper(c) (c >='A'&& c <='Z')
    #defineis_alpha(c) (is_lower(c) ||is_upper(c))
    #defineis_digit(c) (c >='0'&& c <='9')
    #definemin(a, b) ((a) < (b) ? (a) : (b))
    #definemax(a, b) ((a) > (b) ? (a) : (b))
    #definePIacos(-1)
    #defineIO
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    #defineFor(i, a, b) for (int i = a; i <= b; i++)
    typedef long long ll;
    typedef unsigned long long ull;
    typedef pair<int, int> pii;
    typedef pair<ll, ll> pll;
    typedef vector<int> vi;
    const ll inf = 0x3f3f3f3f;
    const double EPS = 1e-10;
    const ll inf_ll = (ll)1e18;
    const ll maxn = 100005LL;
    const ll mod = 1000000007LL;
    const int N = 10000+5;
    /*
    题目:
    给出两个相同长度的由字符 a 和 b
    构成的字符串,定义它们的距离为对应位置不同的字符的数量。如串”aab”与串”aba”的距离为
    2;串”ba”与串”aa”的距离为 1;串”baa”和串”baa”的距离为 0。下面给出两个字符串 S 与
    T,其中 S 的长度不小于 T 的长度。我们用|S|代表 S 的长度,|T|代表 T
    的长度,那么在 S 中一共有|S|-|T|+1 个与T长度相同的子串,现在你需要计算 T
    串与这些|S|-|T|+1 个子串的距离的和。

    输入描述:
    第一行包含一个字符串 S。第二行包含一个字符串 T。S 和 T 均由字符 a 和 b 组成,1 ≤
    |T| ≤ |S| ≤105 。

    输出描述:
    输出对应的答案。

    样例:
    in:
    aab
    aba
    out:
    2
    in:
    aaabb
    bab
    out:
    5*/
    char S[N],T[N];
    int main() {
    cin>>S>>T;
    int lens = strlen(S);
    int lent = strlen(T);
    int a = 0, b = 0, ans = 0;
    for(int i = 0; i< lens - lent +1; i++)
    S[i] == 'a' ? a++ : b++;
    for(int i = 0; i < lent; i++) {
    ans += T[i] == 'a' ? b : a;
    S[i] == 'a' ? a-- : b--;
    S[i + lens - lent + 1] == 'a' ? a++ : b++;
    }
    cout << ans << endl;
    }
    宝剑锋从磨砺出 梅花香自苦寒来
  • 相关阅读:
    剑指offer-整数中1出现的次数
    数据流中的中位数
    二叉搜索树的后序遍历序列
    Java 线程阻塞和唤醒
    Java 线程池
    Python哈希表和解析式
    Python线性数据结构
    python 基础知识
    pyenv虚拟环境管理python多版本和软件库
    Paramiko的SSH和SFTP使用
  • 原文地址:https://www.cnblogs.com/GHzcx/p/8651843.html
Copyright © 2020-2023  润新知