题解 | #牛群的信息传递#
牛群的信息传递
https://www.nowcoder.com/practice/0130cb88968a441b9eedbc103466d2bf
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param message string字符串 * @param keyword string字符串 * @return int整型 */ int findKeyword(string message, string keyword) { // write code here vector<vector<int>> dp(keyword.size() + 1,vector<int>(message.size() + 1,0)); for (int i = 1;i <= keyword.size();++i) { for (int j = 1;j < message.size();++j) { if (keyword[i - 1] == message[j - 1]) { dp[i][j] = dp[i - 1][j - 1] + 1; } } } int index = -1; for (int i = 1;i <= message.size();++i) { if (dp[keyword.size()][i] == keyword.size()) { index = i; break; } } if (index == -1) { return -1; } return index - keyword.size(); } };
那就借助动态规划吧~~~