[LeetCode 周赛184] 1. 数组中的字符串匹配(暴力、常规解法)

1. 题目来源

链接:5380. 数组中的字符串匹配

2. 题目说明

在这里插入图片描述

3. 题目解析

方法一:暴力+常规解法

水题一个,采用直接进行暴力判断即可,string 中的 find 方法进行子串匹配即可。

参见代码如下:

// 执行用时 :8 ms, 在所有 C++ 提交中击败了100.00%的用户
// 内存消耗 :8.4 MB, 在所有 C++ 提交中击败了100.00%的用户

class Solution {
public:
    vector<string> stringMatching(vector<string>& words) {
        vector<string> vt;
        for (int i = 0; i < words.size(); ++i) {
            for (int j = 0; j < words.size(); ++j) {
                if (i == j) continue;
                if (words[j].find(words[i]) != words[j].npos) {
                    vt.push_back(words[i]);
                    break;
                }
            }
        }
        return vt;
    }
};

手速题必备的 auto 版本。

参见代码如下:

// 执行用时 :20 ms, 在所有 C++ 提交中击败了100.00%的用户
// 内存消耗 :9.2 MB, 在所有 C++ 提交中击败了100.00%的用户

class Solution {
public:
    vector<string> stringMatching(vector<string>& words) {
        vector<string> vt;
        for (auto i : words) {
            for (auto j : words) {
                if (i == j) continue;
                if (j.find(i) != -1) {vt.push_back(i); break;}
            }
        }
        return vt;
    }
};
发布了410 篇原创文章 · 获赞 381 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/yl_puyu/article/details/105476864