先看看題目:
1408. String Matching in an Array
Easy
9733Add to ListShareGiven 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 <= 1001 <= words[i].length <= 30words[i]contains only lowercase English letters.- It's guaranteed that
words[i]will be unique.
先附上通關證明:
我的想法:這一題就是說找出陣列裡面短字串有在另一個長字串之中。
其實用include去做就會很簡單。
就兩兩比對,在做長字串是否include短字串就好。
符合條件後就用個key value的物件塞進去,最後再把keys陣列提出就好。
/**
* @param {string[]} words
* @return {string[]}
*/
var stringMatching = function(words) {
var result = {};
for (var i = 0;i<words.length;i++) {
for (var j = i+1 ; j<words.length;j++){
if(i==j)continue;
w1 = words[i]
w2 = words[j]
if(w1.length>w2.length){
if(w1.includes(w2))
result[w2] = true
}else{
if(w2.includes(w1))
result[w1] = true
}
}
}
return Object.keys(result);
};
文章標籤
全站熱搜
