简单题我重拳出击
看一下数据量,
直接暴力
class Solution {
public List<String> stringMatching(String[] words) {
Set<String> list = new HashSet<>();
for (int i = 0; i < words.length; i++){
for (int j = 0; j < words.length; j++){
if (i == j){
continue;
}
if (words[j].indexOf(words[i]) != -1){
list.add(words[i]);
}
}
}
return new ArrayList<>(list);
}
}
另一个解法:拼接字符串,可以把时间复杂度降低到o(n);
class Solution {
public List<String> stringMatching(String[] words) {
List<String> res = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for (String word : words) {
sb.append(word).append(",");
}
for (String word : words){
if (sb.indexOf(word) != sb.lastIndexOf(word)){
res.add(word);
}
}
return res;
}
}