1. 程式人生 > >騰訊筆試經驗-不是大牛-勿看

騰訊筆試經驗-不是大牛-勿看

2018.9.16

1.字串係數。字串A和B,找到B中有A的多少個長度為k的子串。

思路:找到A中長度為k的子串,存到set裡。

           找B中的長度為k的子串,若在set裡有就++。   

只通過90%。

#include <iostream>
#include <string>
#include <set>
#include <vector>
#include <map>
using namespace std;
int main(){
	int k;
	cin>>k;
	string a,b;
	cin>>a>>b;
	int an = a.size();
	int bn = b.size();
	set<string> aa;
	map<string,int> bb;

	for (int i=0;i<an-k+1;i++)
	{		
		string t = a.substr(i, k);
		aa.insert(t);
		cout << t.c_str()<<endl;
	}
	int res = 0;
	for (int i = 0; i < bn-k+1; i++)
	{
		string t = b.substr(i,k);
		if (aa.count(t))
			res++;
	}
	cout<<res;

	return 0;
}

2. 前n個數的和為x+y,求至少需要其中幾個數相加得x,剩下的剛好為y。   

.

思路:兩個數m和n,首先看x+y是否剛好為前t項和,否則返回-1。

           從1到n中找出等於x的最少需要幾個數:

           1.若x<=n  返回1

           2.從後向前計算,若x<=最後兩個數的和, 返回2

             。。。。。。。。。。。。。。。。。。

好吧,這是看了別人的思路得到的,我想複雜了,老想找到哪幾個數,其實只要求出個數就好了!!!!!哎!沒來得及測試的

#include <iostream>
#include <math.h>
using namespace std;
int reachNumber(int x, int y) {
	int res = 0;
	int target = x + y;
	int n = ceil((-1.0 + sqrt(1 + 8.0*target)) / 2);
	int sum = n * (n + 1) / 2;
	if (sum != target){
		res = -1;
		return res;
	}
	int temp = 0;
	for (int i = n; i >= 1; i--){
		temp+=i;
		if (x <= temp){
			return (n + 1 - i);
		}
	}

}

int main(){
	int x, y;
	cin >> x >> y;
	int num = reachNumber(x, y);
	cout << num;
	return 0;
}