面试题 17.05
Solutions
class Solution {
public:
vector<string> findLongestSubarray(vector<string>& array) {
int n = array.size();
// m stores the index of the first appearance of a certain `n_num - n_char`
unordered_map<int, int> m;
m[0] = -1;
// donot explicitly record the number of characters/numbers respectively.
// only their count diffference matters.
int diff = 0, maxlen = 0, minst = 0;
for (int i = 0; i < n; i++) {
diff += isdigit(array[i][0]) ? 1 : -1;
if (!m.count(diff))
m[diff] = i;
else if (i - m[diff] > maxlen || m[diff] + 1 < minst) {
minst = m[diff] + 1;
maxlen = i - m[diff];
}
}
return {array.begin() + minst, array.begin() + minst + maxlen};
}
};Last updated