最近做的一道面试题,面试的时候没写好
作者:
RwChen
,
2023-09-12 11:36:28
,
所有人可见
,
阅读 126
#include <bits/stdc++.h>
using namespace std;
// 根据&&分割字符串
vector<string> resolve(const string& str) {
const int n = str.size();
char *tmp = new char[n];
// char tmp[n];
vector<string> res;
int len = 0;
for (int i = 0; i < n; ++i) {
tmp[len++] = str[i];
if (len >= 2 && tmp[len - 1] == '&' && tmp[len - 2] == '&') {
tmp[len - 2] = '\0';
if (len > 2) res.push_back(tmp);
len = 0;
}
}
if (len) {
tmp[len] = '\0';
res.push_back(tmp);
}
delete tmp;
return res;
}
int main() {
auto res = resolve("&&a&&b&");
for (auto &x : res) cout << x << '\n';
return 0;
}
函数如果多次调用tmp数组那里可以优化一下
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5;
// 根据&&分割字符串
vector<string> resolve(const string& str) {
const int n = str.size();
static char tmp[MAXN];
vector<string> res;
int len = 0;
for (int i = 0; i < n; ++i) {
tmp[len++] = str[i];
if (len >= 2 && tmp[len - 1] == '&' && tmp[len - 2] == '&') {
tmp[len - 2] = '\0';
if (len > 2) res.push_back(tmp);
len = 0;
}
}
if (len) {
tmp[len] = '\0';
res.push_back(tmp);
}
return res;
}
int main() {
auto res = resolve("&&a&&b&");
for (auto &x : res) cout << x << '\n';
return 0;
}