class Solution {
public List<String> stringMatching(String[] words) {
if (words == null || words.length == 0) {
return new ArrayList<>();
}
HashSet<String> set = new HashSet<>();
for (String i : words) {
if (!set.contains(i)) {
for (String j : words) {
if (j.contains(i) && !j.equals(i)) {
set.add(i);
break;
}
}
}
}
return new ArrayList<>(set);
}
}
or
StringBuilder builder = new StringBuilder();
for (String word : words) {
builder.append(word).append(",");
}
String wholeWords = builder.toString();
List<String> resultList = new ArrayList<>();
for (String word : words) {
int index1 = wholeWords.indexOf(word);
int index2 = wholeWords.lastIndexOf(word);
if (index1 >= 0 && index2 >= 0 && index1 != index2) {
resultList.add(word);
}
}
return resultList;
```