当前位置:网站首页>Leek 1408. String matching in arrays
Leek 1408. String matching in arrays
2022-08-07 10:33:00 【cold-blooded fisherman】
题目
给你一个字符串数组 words ,数组中的每个字符串都可以看作是一个单词.请你按 任意 顺序返回 words 中是其他单词的子字符串的所有单词.
如果你可以删除 words[j] 最左侧和/或最右侧的若干字符得到 word[i] ,那么字符串 words[i] 就是 words[j] 的一个子字符串.
示例
输入:words = [“mass”,“as”,“hero”,“superhero”]
输出:[“as”,“hero”]
解释:“as” 是 “mass” 的子字符串,“hero” 是 “superhero” 的子字符串.
[“hero”,“as”] 也是有效的答案.
输入:words = [“leetcode”,“et”,“code”]
输出:[“et”,“code”]
解释:“et” 和 “code” 都是 “leetcode” 的子字符串.
输入:words = [“blue”,“green”,“bu”]
输出:[]
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/string-matching-in-an-array
著作权归领扣网络所有.商业转载请联系官方授权,非商业转载请注明出处.
方法1:暴力模拟
Java实现1
class Solution {
public List<String> stringMatching(String[] words) {
List<String> res = new ArrayList<>();
int n = words.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) continue;
if (words[j].indexOf(words[i]) != -1) {
res.add(words[i]);
break;
}
}
}
return res;
}
}

Java实现2
使用lambdaexpression firstwordsArrays are sorted by length from smallest to largest.
class Solution {
public List<String> stringMatching(String[] words) {
List<String> res = new ArrayList<>();
int n = words.length;
Arrays.sort(words, (a, b) ->{
return a.length() - b.length();
});
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (words[j].indexOf(words[i]) != -1) {
res.add(words[i]);
break;
}
}
}
return res;
}
}

边栏推荐
猜你喜欢

QT练手小项目:飞机大战

During the meeting, I was scolded by the leader for more than 10 minutes. The scolding made me almost cry, and my voice was shaking.

一文讲清-DeFI王者AAVE最新的稳定币GHO提案

Flask Framework - Application Error Handling

MySQL中删除命令的区别(delete、truncate、drop)

How does Apache, the world's largest open source foundation, work?

命令执行漏洞

SQL 获取每个部门中当前员工薪水最高的相关信息

xlwings module (data is saved as xlsx file)

MapStruct 高级用法
随机推荐
搭一个K3S 玩玩
[.NET6+Modbus] Modbus TCP protocol analysis, simulation environment and basic communication based on .NET
UGUI系列-原理分析(Unity3D)
使用对象流传输Student类
Knowledge of Node
UGUI系列-Button绑定事件的多种实现
Project optimization loop optimization (Unity3D)
UGUI Series - Multiple Implementations of Button Binding Events
UGUI系列-Dropdown控件研究(Unity3D)
100天精通Andriod逆向——第1天:ADB原理及其常用命令
UGUI系列-屏幕自适应多分配率适配(Untiy3D)
求职面试、笔试 经验与准备流程
查询文件和目录的磁盘使用
Custom Annotations and Reflections
Display variables and classes in the Inspector panel (Unity3D)
Want to save programs?The dongle is too much trouble, try this (Unity3D)
力扣 1408. 数组中的字符串匹配
数据库分表之雪花算法
颜值爆表!Redis官方可视化工具来啦,功能真心强大!
360 Enterprise Security Cloud debuts at the 2022 Global Digital Economy Conference to consolidate the digital foundation of small, medium and micro enterprises