【发布时间】:2014-02-13 08:57:25
【问题描述】:
找出两个字符串共有的最大字符数。字符区分大小写,即小写和大写字符被认为是不同的。
这是我的代码:
#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 秒内完成。有什么优化技巧吗?
【问题讨论】:
-
这更适合CodeReview。
-
对于初学者,请定义“有共同点”。根据含义,最简单的解决方案是对字符串进行排序,然后对它们进行比较。 (字符串有多长?尽管是 O(n^2),但我希望您的代码几乎可以立即完成正常长度的字符串。)
-
是来自
currently running programming contestcodechef.com/FEB14/problems/LCPESY 吗?你提到1 sec。我认为这不应该回答。
标签: c++ string algorithm stl comparison