笔试题

求两个字符串的最长公共子串(快手)

  • 动态规划求解。二维动规
  • 代码如下:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

int get_longest_common_substring(string a, string b) {
	int len_a = a.size();
	int len_b = b.size();
	if (len_a > len_b) {
		string tmp = a;
		a = b; 
		b = tmp;
	}
	vector<vector<int>> dp(a.size() + 1, vector<int>(b.size() + 1));
	dp[0][0] = 0;
	int max = 0;
	for (int i = 1; i <= a.size(); i++) {
		for (int j = 1; j <= b.size(); j++) {
			if (a[i - 1] == b[j - 1]) {
				dp[i][j] = dp[i - 1][j - 1] + 1;
			}
			else {
				dp[i][j] = dp[i - 1][j - 1];
			}
			if (dp[i][j] > max) max = dp[i][j];
		}
	}
	return max;
}

int main() {
	string s;
	cin >> s;
	string a;
	string b;
	int par = 0;
	for (int i = 0; i < s.size(); i++) {
		while (i < s.size() && s[i++] != ',') 
			par++;
		break;
	}
	a = s.substr(0, par);
	b = s.substr(par + 1, s.size() - 1 - par);
	int res = get_longest_common_substring(a, b);
	return 0;
}

紧急疏散(京东)
输入:
6
2 1
3 2
4 3
5 2
6 1
数对表示连接关系。其中1是根节点。

  • 可以转化成求树的最大深度
#include <iostream>
#include <vector>
#include <utility>
#include <unordered_map>

using namespace std;


vector<pair<int, int> > cnn;
unordered_map<int, bool> hash_map; //int中存的是pair的下标

int dfs(int p) {
	int res = 0;
	int max = 0;
	for (int i = 0; i < cnn.size(); i++) {
		if (!hash_map[i] && cnn[i].second == p) {
			hash_map[i] = true;
			res = dfs(cnn[i].first) + 1;
		}
		if (res > max) max = res; //当有多个分支时, 保留深度最深的那个分支的深度
	}
	return max;
}

int main() {
	int n;
	cin >> n;
	
	unordered_map<int, bool> _hash;
	hash_map = _hash;
	int i = 0;
	while (--n) {
		int a, b;
		cin >> a >> b;
		pair<int, int> tmp = pair<int, int>{a, b};
		cnn.push_back(tmp);
		hash_map[i++] = false;
	}

	int ans = dfs(1) + 1;

	cout << ans << endl;

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值