2018美团笔试字符串问题
生活随笔
收集整理的這篇文章主要介紹了
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。第二行包含一個字符串?T。S?和?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)。
這題題中給出了只有a,b兩種字母,那有其他字母該怎么搞呢,其實一樣的,只不過把代碼中的a,?b變量用一個長度為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; }
轉載于:https://www.cnblogs.com/GHzz/p/8651843.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的2018美团笔试字符串问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python之numpy库
- 下一篇: 【Python】远离 Python 最差