Given an array of string
String
words
. Return all strings in words
which is a 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: ["hero","as"]
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.HashSet;import java.util.Iterator;import java.util.List;public class StringMatchingInArray {public static void main(String[] args) {String[] words = { "mass", "as", "hero", "superhero" };List<String> match = stringMatching(words);System.out.println(Arrays.asList(match));}static List<String> stringMatching(String[] words) {List<String> res = new ArrayList<String>();HashSet<String> st = new HashSet<String>();int n = words.length;for (int i = 0; i < n; i++) {String str = words[i];for (int j = 0; j < n; j++) {String s = words[j];if (i != j) {if (s.length() >= str.length()) {for (int k = 0; k <= s.length() - str.length(); k++) {int flag = 0;for (int l = 0; l < str.length(); l++) {if (str.charAt(l) != s.charAt(l + k)) {flag = 1;break;}}if (flag == 0) {st.add(str);break;}}}}}}Iterator<String> it = st.iterator();while (it.hasNext())res.add(it.next());return res;}}
C++
#include <bits/stdc++.h>using namespace std;vector<string> stringMatching(vector<string> &words){vector<string> res;unordered_set<string> st;int n = words.size();for (int i = 0; i < n; i++){string str = words[i];for (int j = 0; j < n; j++){string s = words[j];if (i != j){if (s.size() >= str.size()){for (int k = 0; k <= s.size() - str.size(); k++){int flag = 0;for (int l = 0; l < str.size(); l++){if (str[l] != s[l + k]){flag = 1;break;}}if (flag == 0){st.insert(str);break;}}}}}}for (auto it = st.begin(); it != st.end(); it++)res.push_back(*it);return res;}int main(){vector<string> words = {"mass", "as", "hero", "superhero"};vector<string> match = stringMatching(words);for (int i = 0; i < match.size(); i++)cout << match[i] << " ";return 0;}
No comments:
Post a Comment