当前位置:网站首页>[1408. String matching in arrays]
[1408. String matching in arrays]
2022-08-07 00:15:00 【Thousands of north @】
来源:力扣(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] 都是独一无二的.
方法:暴力枚举
for a string in an array of strings words[i],We judge whether it is a substring of other strings,只需要枚举 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 is the length of the longest string in the string array.使用 KMP The string matching algorithm can optimize the time complexity to O(n2 × T),其中 T is the average length of all strings in the string array.
空间复杂度: O(1).返回值不计入空间复杂度.如果使用 KMP 字符串匹配算法,Then the corresponding space complexity is O(T).
author:LeetCode-Solution
边栏推荐
猜你喜欢

Flutter APNS device token not set before retrieving FCM Token for Sender ID

阿帽的新画

ansible 一题多解

CV领域经典backbone模型小抄(2)

2022年G2电站锅炉司炉题库及在线模拟考试

[TA-Frost Wolf_may-"Hundred Talents Project"] Graphics 4.4 Introduction to Anti-Aliasing

Vi learning (2) the common commands include move cursor/highlight the text/undo and the undo/delete/copy and paste the text/find replacement/insert 】

数据类型float存储结构的理解

leetcode 19. 删除链表的倒数第 N 个结点

LVS+Keepalive cluster
随机推荐
对比学习模型小抄(1)
2022.8.4 Mock Competition
Zscoder‘s 生成函数教程(二)
【微服务架构】链路追踪Skywalking入门与实践
自动化测试真的有被需要吗?
php three-dimensional array merge and accumulate their values according to a key
LVS+Keepalive群集
【Redis】Redis学习——三种特殊数据类型
【7】C语言进阶--程序的编译(预处理操作)+链接
Playwright安装加一个简单的实例
【使用JDBC对数据库表进行操作】
多项式——多项式牛顿迭代
Ftrace function graph简介
Can wechat applet and qq applet be developed on the same cloud?
Commonly used mail servers support ports and encryption methods measured
炒股用通达信交易靠谱吗?安全吗?
NAT穿越技术详细介绍
多项式与生成函数教程合集
【验证用户输入的日期格式是否正确——工具类SimpleDateFormat类的使用】
双指针——移除元素