• LeetCode 1408. 数组中的字符串匹配


    【LetMeFly】1408.数组中的字符串匹配

    力扣题目链接:https://leetcode.cn/problems/string-matching-in-an-array/

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

    方法一:字符串暴力匹配

    两层循环遍历字符串数组,如果第一层循环到的字符串是第二层循环到的字符串的子串,就把第一层循环的字符串添加到答案中,并结束第二层循环。

    • 时间复杂度KaTeX parse error: Undefined control sequence: \tiems at position 6: O(n^2\̲t̲i̲e̲m̲s̲ ̲L^2),其中 n n n是原始字符串数组的长度, L L L是平均每个字符串的长度
    • 空间复杂度 O ( 1 ) O(1) O(1),答案不计入算法复杂度

    AC代码

    C++

    class Solution {
    public:
        vector<string> stringMatching(vector<string>& words) {
            vector<string> ans;
            int n = words.size();
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    if (i == j)
                        continue;
                    if (words[j].find(words[i]) < words[j].size()) {
                        ans.push_back(words[i]);
                        break;
                    }
                }
            }
            return ans;
        }
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    同步发文于CSDN,原创不易,转载请附上原文链接哦~
    Tisfy:https://letmefly.blog.csdn.net/article/details/126189255

  • 相关阅读:
    【以太网硬件十四】以太网的MAC是干什么的?
    TLS回调函数
    Java并发之线程池
    干货 | 科研人的KPI怎么算,H指数和G指数是什么
    Power Apps使用oData访问表数据并赋值前端
    Kubernetes 介绍
    react:封装组件
    MapReduce执行流程
    Intellij IDEA--解决项目名后带中括号的问题
    几种点云(网格)孔洞填充方法(1)
  • 原文地址:https://blog.csdn.net/Tisfy/article/details/126189255