1408. 数组中的字符串匹配『简单』

题目来源于力扣(LeetCode

一、题目

1408. 数组中的字符串匹配

题目相关标签:字符串

提示:

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 30
  • words[i] 仅包含小写英文字母。
  • 题目数据 保证 每个 words[i] 都是独一无二的。

二、解题思路

2.1 暴力法

  1. 遍历 words 数组,对于每个遍历的元素都进行全局的遍历,判断当前元素是否为其他数组元素的子字符串(子字符串而不子序列),使用 indexOf() 方法

  2. 遍历找到当前元素为数组元素的子字符串时,结束(break)内层循环

    题意是要返回 words 中是其他单词的子字符串的单词

2.2 缓冲字符串方式

  1. 因 words 数组中元素长度并不大,遍历 words 数组,将数组元素添加到缓冲字符串中,元素与元素之间使用英文逗号分隔

  2. 遍历 nums 数组,使用 indexOf()lastIndexOf() 方法来判断当前遍历字符串是否为其他字符串的子字符串(即 indexOf() 的结果与 lastIndexOf() 结果不一致

三、代码实现

3.1 暴力法

public static List<String> stringMatching(String[] words) {
    List<String> ans = new ArrayList<>();
    for (int i = 0; i < words.length; i++) {
        for (int j = 0; j < words.length; j++) {
            // 排除索引相同和字符串长度小于的情况(小于时则一定不包括该串)
            if (i == j || words[i].length() > words[j].length()) {
                continue;
            }
            if (words[j].indexOf(words[i]) > -1) {
                ans.add(words[i]);
                // break 而不是 continue,证明 当前遍历元素是其他单词的子字符串 即完成 
                break;
            }
        }
    }
    return ans;
}

3.2 缓冲字符串方式

public static List<String> stringMatching(String[] words) {
    List<String> list = new ArrayList<>();
    StringBuilder sb = new StringBuilder();
    // 因 words 的长度不大,所以将 words 中的元素添加到字符串中,串与串使用 "," 分隔
    for (String word : words) {
        sb.append(word).append(",");
    }
    for (String word : words) {
        // 说明有两处以上的位置存在 word 时,添加到结果集
        if (sb.indexOf(word) != sb.lastIndexOf(word)) {
            list.add(word);
        }
    }
    return list;
}

四、执行用时

4.1 暴力法

4.2 缓冲字符串方式

五、部分测试用例

public static void main(String[] args) {
    String[] words = {"mass", "as", "hero", "superhero"};  // output:{"as", "hero"}
//    String[] words = {"leetcoder","leetcode","od","hamlet","am"};  // output:{"leetcode", "od", "am"}
//    String[] words = {"leetcode", "et", "code"};  // output:{"et", "code"}
//    String[] words = {"blue", "green", "bu"};  // output:{}

    List<String> result = stringMatching(words);
    System.out.println(result);
}
posted @ 2020-05-31 18:12  知音12138  阅读(512)  评论(0编辑  收藏  举报