c++ - 查找两个字符串共有的最大字符数

标签 c++ string algorithm stl comparison

找出两个字符串共有的最大字符数。字符区分大小写,即小写和大写字符被认为是不同的。

这是我的代码:

#include <iostream>
#include <cstring> 
using namespace std;

int main() {
    std::string a, b;
    int number_cases = 0, count = 0;
    cin >> number_cases;
    while (number_cases != 0) {
        cin >> a;
        cin >> b;
        for (int i = 0; i < a.size(); i++) {
            for (int j = 0; j < b.size(); j++) {
                if (a[i] == b[j]) {
                    count++;
                    b[j] = '#';
                    break;
                }
            }
        }
        cout << count << endl;
        count = 0;
        --number_cases;
    }
}

但运行时间超过 1 秒,我需要将其控制在 1 秒以下或恰好 1 秒。有什么优化技巧吗?

最佳答案

只需对它们进行排序并使用 set_intersection

#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>

int main()
{
    std::string s1 = "Hello";
    std::string s2 = "World";

    std::sort(begin(s1), end(s1));
    std::sort(begin(s2), end(s2));

    std::string s3;
    std::set_intersection(begin(s1), end(s1), begin(s2), end(s2), std::back_inserter(s3));
    std::cout << s3.size() << ":" << s3;
}

Live Example .

注意:如果您对独特的重叠字符感兴趣,可以在s3 上运行std::unique

关于c++ - 查找两个字符串共有的最大字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21749310/

相关文章:

python - 在 python 中使用 str.format 时的引号

c++ - 该代码中的错误是什么?

algorithm - 如何最佳解决洪水填充难题?

database - 提高定位行(整数列)的速度

c++ - 对具有不可复制值的 STL 容器使用 boost 序列化时出现编译错误

c++ - 了解 std::condition_variables

c++ - 将元素插入排序 vector 并保持元素排序

c++ - 标签上的绑定(bind)循环警告

string - 如何在 swift 3.0 中连接多个可选字符串?

algorithm - 确定点相对于给定 3D 表面的位置