第一场leetcode周赛,10:45才想起来。
比赛链接:https://leetcode.com/contest/weekly-contest-141/
前两道都是逻辑题,比较简单,但是读题太慢了,加上C++语法不熟悉,老是出错。
第三道1091 bfs,直接记录步数,当前位置的相邻位置没有访问过或者步数更新了时,加入队列。没有任何技巧的bfs。还是读题没读懂,耽误了很久。
第四道是hard难度的题。看题解写出来的。
题目链接:1092. Shortest Common Supersequence
给两个字符串str1, str2,求一个字符串s,str1和str2都是s的子序列,s要求最小长度。
思路:
先求出LCS,然后遍历两个字符串,如果当前字符在LCS里,加入ans,否则加入那个不在LCS的字符。即在LCS中插入剩余字符。
代码:
class Solution {
public:
string shortestCommonSupersequence(string str1, string str2) {
int l1 = str1.length();
int l2 = str2.length();
vector<vector<int> > dp(l1+1, vector<int>(l2+1, 0));
dp[0][0] = (str1[0] == str2[0] ? 1 : 0);
for (int i=1; i<=l1; ++i) {
for (int j=1; j<=l2; ++j) {
if (str1[i-1] == str2[j-1]) dp[i][j] = dp[i-1][j-1] + 1;
else dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
}
}
string ans = "";
while(l1 || l2) {
char temp;
if (l1 <= 0) temp = str2[--l2];
else if (l2 <= 0) temp = str1[--l1];
else if (str1[l1-1] == str2[l2-1]) temp = str1[--l1] = str2[--l2];
else temp = (dp[l1][l2] == dp[l1-1][l2] ? str1[--l1] : str2[--l2]);
ans += temp;
}
reverse(ans.begin(), ans.end());
return ans;
}
};
感觉这道题还是稀里糊涂的。
这周周赛继续。
昨天晚上又熬夜看剧。。。。惨案。
真的不能考验自己的自制力。远离诱惑。
这周还是继续看faster rcnn源码吧…不知道自己整天都在干什么。。。。