侧边栏壁纸
博主头像
GabrielxD

列車は必ず次の駅へ。では舞台は?私たちは?

  • 累计撰写 674 篇文章
  • 累计创建 128 个标签
  • 累计收到 20 条评论

目 录CONTENT

文章目录

【暴力, 枚举, 字符串】数组中的字符串匹配

GabrielxD
2022-08-06 / 0 评论 / 0 点赞 / 188 阅读 / 483 字
温馨提示:
本文最后更新于 2022-08-06,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

题目

1408. 数组中的字符串匹配


给你一个字符串数组 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] 都是独一无二的。

解题

方法一:暴力 枚举 字符串

思路

对于字符串数组中的某个字符串 a,判断它是否是其他字符串的子字符串,只需要再次枚举数组中每个字符串 b,如果 a != bab 的子字符串,那么就可以把 a 加入结果中。

代码

class Solution {
public:
    vector<string> stringMatching(vector<string>& words) {
        vector<string> ans;
        for (string& a : words) {
            for (string& b : words) {
                if (a != b && b.find(a) != string::npos) {
                    ans.push_back(a);
                    break;
                }
            }
        }
        return ans;
    }
};
class Solution {
    public List<String> stringMatching(String[] words) {
        List<String> ans = new ArrayList<>();
        for (String a : words) {
            for (String b : words) {
                if (!a.equals(b) && b.contains(a)) {
                    ans.add(a);
                    break;
                }
            }
        }
        return ans;
    }
}
0

评论区