此博客鏈接:https://www.cnblogs.com/ping2yingshi/p/12897829.html
數組中的字符串匹配(115min)
題目鏈接:https://leetcode-cn.com/problems/string-matching-in-an-array/
給你一個字符串數組 words ,數組中的每個字符串都可以看作是一個單詞。請你按 任意 順序返回 words 中是其他單詞的子字符串的所有單詞。
如果你可以刪除 words[j] 最左側和/或最右側的若干字符得到 word[i] ,那么字符串 words[i] 就是 words[j] 的一個子字符串。
示例 1:
輸入:words = ["mass","as","hero","superhero"]
輸出:["as","hero"]
解釋:"as" 是 "mass" 的子字符串,"hero" 是 "superhero" 的子字符串。
["hero","as"] 也是有效的答案。
示例 2:
輸入:words = ["leetcode","et","code"]
輸出:["et","code"]
解釋:"et" 和 "code" 都是 "leetcode" 的子字符串。
示例 3:
輸入:words = ["blue","green","bu"]
輸出:[]
提示:
1 <= words.length <= 100
1 <= words[i].length <= 30
words[i] 僅包含小寫英文字母。
題目數據 保證 每個 words[i] 都是獨一無二的。
題解:
思路:
1.雙重循環。
2.每遍歷一個元素,把這個元素和其他元素相比較,如果其他元素包含這個元素,則把這個元素加入到列表中。
注意:當遍歷到自己時,跳出這次循環判斷,進行下一次循環判斷。
代碼如下:
class Solution { public List<String> stringMatching(String[] words) { LinkedList<String> str = new LinkedList<>(); for(String i:words) { for(String j:words) { if (i.equals(j)) { continue; } if(j.contains(i)) { str.add(i); break; } } } return str; } }