鏈接:leetcode 5380. 數組中的字符串匹配
來源:力扣(LeetCode)
給你一個字符串數組 words ,數組中的每個字符串都可以看作是一個單詞。請你按 任意 順序返回 words 中是其他單詞的子字符串的所有單詞。
如果你可以刪除 words[j] 最左側和/或最右側的若干字符得到 word[i] ,那麼字符串 words[i] 就是 words[j] 的一個子字符串。
示例 1:
輸入:words = [“mass”,“as”,“hero”,“superhero”]
輸出:[“as”,“hero”]
解釋:“as” 是 “mass” 的子字符串,“hero” 是 “superhero” 的子字符串。
[“hero”,“as”] 也是有效的答案。
示例 2:
輸入:words = [“leetcode”,“et”,“code”]
輸出:[“et”,“code”]
解釋:“et” 和 “code” 都是 “leetcode” 的子字符串。
示例 3:
輸入:words = [“blue”,“green”,“bu”]
輸出:[]
提示:
1 <= words.length <= 100
1 <= words[i].length <= 30
words[i] 僅包含小寫英文字母。
題目數據 保證 每個 words[i] 都是獨一無二的。
思路分析
就是直接暴力匹配就行。
從所需要查找的字符串開始,往左邊,再往右邊查找,若找到一個符合要求即可。
代碼解析
class Solution {
bool Match_words(string yanzhen, string yizhi) {
int count = 0, k = 0;
for (int i = 0, j = 0; j < yizhi.size() && i < yanzhen.size();) {
if (yanzhen[i] == yizhi[j]) {
i++;
j++;
count++;
}
else {
count = 0;
i = 0;
j = ++k;
}
if (count == yanzhen.size())
return true;
}
return false;
}
public:
vector<string> stringMatching(vector<string>& words) {
int num = words.size();
vector<string> new_words;
for (int i = 0; i < num; i++) {
int flag = 0;
for (int j = i + 1; j < num; j++) {
if (Match_words(words[i], words[j])) {
new_words.push_back(words[i]);
flag = 1;
break;
}
}
for (int k = i - 1; flag == 0 && k >= 0; --k) {
if (Match_words(words[i], words[k])){
new_words.push_back(words[i]);
break;
}
}
}
return new_words;
}
};