【暴力】数据量不大,直接暴力了,java中contains可以用来判断一个字符串是否包含另一个字符串,但是要注意最后答案不能包含重复的字符串哦。
class Solution {
// 暴力 3:20 1
public List<String> stringMatching(String[] words) {
List<String> ans = new ArrayList();
int i, j, n = words.length;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (i != j && words[j].contains(words[i])) {
ans.add(words[i]); break;
}
}
}
return ans;
}
}
class Solution {
public:
// 暴力 3:23 2
vector<string> stringMatching(vector<string>& words) {
int i, j, n= words.size();
vector<string> ans;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (i != j && words[j].find(words[i]) != -1) {
ans.push_back(words[i]); break;
}
}
}
return ans;
}
};
【哈希+分割字符串】自己想的方法,但是慢
class Solution {
// 哈希表 12:49
public List<String> stringMatching(String[] words) {
Set<String> set = new HashSet();
for (var str: words) set.add(str);
List<String> ans = new ArrayList();
for (var st: words) {
String str = st;
int n = str.length();
for (var i = 0; i < n; i++) {
for (var j = i + 1; j <= n; j++) {
String tmp = str.substring(i, j);
if (!tmp.equals(str) && set.contains(tmp)) {
ans.add(tmp);
set.remove(tmp);
}
}
}
}
return ans;
}
}