当前位置:网站首页>【1408. 数组中的字符串匹配】
【1408. 数组中的字符串匹配】
2022-08-07 00:10:00 【千北@】
来源:力扣(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] 都是独一无二的。
方法:暴力枚举
对于字符串数组中的某个字符串 words[i],我们判断它是否是其他字符串的子字符串,只需要枚举 words[j],其中 j != i ,如果 words[i] 是 words[j] 的子字符串,那么将 words[i] 加入结果中。
代码:
class Solution {
public:
vector<string> stringMatching(vector<string>& words) {
vector<string> ret;
for (int i = 0; i < words.size(); i++) {
for (int j = 0; j < words.size(); j++) {
if (i != j && words[j].find(words[i]) != string::npos) {
ret.push_back(words[i]);
break;
}
}
}
return ret;
}
};
执行用时:4 ms, 在所有 C++ 提交中击败了92.18%的用户
内存消耗:8 MB, 在所有 C++ 提交中击败了96.30%的用户
复杂度分析
时间复杂度: O(n2 × L2),其中 n 是字符串数组的长度, L 是字符串数组中最长字符串的长度。使用 KMP 字符串匹配算法可以将时间复杂度优化到 O(n2 × T),其中 T 是字符串数组中所有字符串的平均长度。
空间复杂度: O(1)。返回值不计入空间复杂度。如果使用 KMP 字符串匹配算法,那么对应的空间复杂度为 O(T)。
author:LeetCode-Solution
边栏推荐
- 多项式——多项式函数
- 多项式——乘法逆元
- Uuid 32-bit data processing, 16
- 读书有利于生活
- Dark horse 2022 latest redis course notes and knowledge points (for interviews) are continuously updated
- P4315 月下“毛景树”(树链剖分)
- 创建文件 Demo1.txt 写入文本 hello 创建文件 Demo2.txt 写入文本 Neuedu 将两个文件内容 提取出来输出到 第三个文件 Test.txt 通过 文件与流方式实现
- (ECCV-2022)GaitEdge:超越普通的端到端步态识别,提高实用性(续)
- 惯性测量单元预积分原理与实现
- 微信小程序跟qq小程序不能用一个云开发吗?
猜你喜欢

Talking about API Gateway

【字符串中处理类String的使用】

SmartIDE v1.0.23 一个非常不敏捷的发布

网页版MC服务器搭建+汉化

logcat: Solution for Unexpected EOF!

Bugku this is a simple picture

Dark horse 2022 latest redis course notes and knowledge points (for interviews) are continuously updated

leetcode 23. 合并K个升序链表

阿帽的新画

mysql数据库中select 基本查询(1)
随机推荐
Close the Win10 automatic updates
微信小程序跟qq小程序不能用一个云开发吗?
strcmp、strstr、memcpy、memmove等库函数的用法和模拟实现
How does the fragment get the click event of the activity
LVS+Keepalive cluster
JCF之List集合实现——Vector
在中国银河证券开户安全吗
平安证券开户怎么样?安不安全
居延安《公共关系学》重点整理
NAT穿越技术详细介绍
【Redis】Redis学习——五大基本数据类型
双指针——移除元素
MySql操作之DDL
多项式——乘法逆元
多项式与生成函数教程合集
jvm总结
网络通信之NIO编程
用同花顺开户安全么
What is the matter with several IP addresses of this machine?to analyze
深入了解集合的使用方法