链接:. - 力扣(LeetCode)
题解:把字母看成1,把数字看为-1,将题目变为求的和为0的最长连续子数组
class Solution {
public:
vector<string> findLongestSubarray(vector<string>& array) {
if (array.size() <= 0) {
return {};
}
std::unordered_map<int, int> table;
table[0] = -1;
int sum = 0;
int len = 0;
int index = 0;
for (int i = 0; i < array.size(); ++i) {
const auto& num = array[i];
if (isalpha(num[0])) {
sum += 1;
} else {
sum -= 1;
}
auto it = table.find(sum);
if (it != table.end()) {
if (i - it->second > len) {
len = i - it->second;
index = it->second+1;
}
} else {
table[sum] = i;
}
}
std:vector<string> result;
result.reserve(len);
for (int i = 0; i < len; ++i) {
result.push_back(array[index+i]);
}
return result;
}
};