给定一个放有字母和数字的数组,找到最长的子数组,且包含的字母和数字的个数相同。
返回该子数组,若存在多个最长子数组,返回左端点下标值最小的子数组。若不存在这样的数组,返回一个空数组。
示例 1:
输入: ["A","1","B","C","D","2","3","4","E","5","F","G","6","7","H","I","J","K","L","M"] 输出: ["A","1","B","C","D","2","3","4","E","5","F","G","6","7"]
示例 2:
输入: ["A","A"] 输出: []
提示:
array.length <= 100000
思路:每个字母对应1,数字对应-1,寻找长度为0的子数组。其中的更新方法就是遍历,找到相同的sum,sum之间的所有数便是一个新的子数组,判断是否更新最大子数组即可。
C++:
class Solution {
public:
vector<string> findLongestSubarray(vector<string>& array) {
unordered_map<int,int> mp;
mp[0] = -1;//起初无前缀时下标为-1
int maxLength = 0;//当前的子数组长度
int start_index = 0;//子数组首下标
int n = array.size();
int sum = 0;
for(int i = 0;i<n;i++){
if(isalpha(array[i][0])) sum++;//如果是字母 sum++
else sum--;
if(mp.count(sum)){//倘若已经存在这个数 则这两个数之间的所有数即为一个新的子数组(之间的数和为0)
int first_index = mp[sum];//新子数组首下标
if(i-first_index>maxLength){//如果新子数组长度大于maxLength 则更换最长子数组
maxLength = i-first_index;//更新最大长度
start_index = first_index+1;//更新子数组首下标
}
}else{//不存在则存入哈希表
mp[sum] = i;
}
}
return vector<string>(array.begin()+start_index,array.begin()+start_index+maxLength);//返回子数组
}
};
Java:
class Solution {
public String[] findLongestSubarray(String[] array) {
HashMap<Integer,Integer> mp = new HashMap<>();
mp.put(0,-1);//起初无前缀时下标为-1
int maxLength = 0;//当前的子数组长度
int startIndex = 0;//子数组首下标
int n = array.length;
int sum = 0;
for(int i = 0;i<n;i++){
if(Character.isLetter(array[i].charAt(0))) sum++;//如果是字母 sum++
else sum--;
if(mp.containsKey(sum)){//倘若已经存在这个数 则这两个数之间的所有数即为一个新的子数组(之间的数和为0)
int first_index = mp.get(sum);//新子数组首下标
if(i-first_index>maxLength){//如果新子数组长度大于maxLength 则更换最长子数组
maxLength = i-first_index;//更新最大长度
startIndex = first_index+1;//更新子数组首下标
}
}else{//不存在则存入哈希表
mp.put(sum,i);
}
}
String[] ans = new String[maxLength];
System.arraycopy(array, startIndex, ans, 0, maxLength);
return ans;
}
}