原文链接: https://leetcode-cn.com/problems/string-matching-in-an-array
英文原文
Given an array of string words
. Return all strings in words
which is substring of another word in any order.
String words[i]
is substring of words[j]
, if can be obtained removing some characters to left and/or right side of words[j]
.
Example 1:
Input: words = ["mass","as","hero","superhero"] Output: ["as","hero"] Explanation: "as" is substring of "mass" and "hero" is substring of "superhero". ["hero","as"] is also a valid answer.
Example 2:
Input: words = ["leetcode","et","code"] Output: ["et","code"] Explanation: "et", "code" are substring of "leetcode".
Example 3:
Input: words = ["blue","green","bu"] Output: []
Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 30
words[i]
contains only lowercase English letters.- It's guaranteed that
words[i]
will be unique.
中文题目
给你一个字符串数组 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]
都是独一无二的。
通过代码
高赞题解
解题思路
两次循环
第一次遍历数组拼接成一个长字符串S
第二次遍历数组查找字符串在S中出现的位置,如果是别人的子串,那么在S中的出现次数一定 >= 2,那么起始跟结束的位置索引一定是不一样的,如果一样说明不是子串。
注意:为了避免前一字符串的尾部与后一字符串的头部构成混淆项,各字符串用,隔开拼接。
代码
class Solution {
public List<String> stringMatching(String[] words) {
List<String> list = new ArrayList<>();
if (words.length == 0) return list;
StringBuilder builder = new StringBuilder();
for (int i = 0; i < words.length; i++){
String str = words[i];
builder.append(str + ",");
}
for (int i = 0; i < words.length; i++){
String str = words[i];
if (builder.toString().indexOf(str) != builder.toString().lastIndexOf(str)) list.add(str);
}
return list;
}
}
统计信息
通过次数 | 提交次数 | AC比率 |
---|---|---|
13934 | 22668 | 61.5% |
提交历史
提交时间 | 提交结果 | 执行时间 | 内存消耗 | 语言 |
---|