求两个字符串的最长公共子串(快手)
- 动态规划求解。二维动规
- 代码如下:
#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;
}