0
点赞
收藏
分享

微信扫一扫

#yyds干货盘点# LeetCode程序员面试金典:字母与数字

题目:

给定一个放有字母和数字的数组,找到最长的子数组,且包含的字母和数字的个数相同。

返回该子数组,若存在多个最长子数组,返回左端点下标值最小的子数组。若不存在这样的数组,返回一个空数组。

示例 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"]

输出: []

代码实现:

class Solution {
public String[] findLongestSubarray(String[] array) {
Map<Integer, Integer> indices = new HashMap<Integer, Integer>();
indices.put(0, -1);
int sum = 0;
int maxLength = 0;
int startIndex = -1;
int n = array.length;
for (int i = 0; i < n; i++) {
if (Character.isLetter(array[i].charAt(0))) {
sum++;
} else {
sum--;
}
if (indices.containsKey(sum)) {
int firstIndex = indices.get(sum);
if (i - firstIndex > maxLength) {
maxLength = i - firstIndex;
startIndex = firstIndex + 1;
}
} else {
indices.put(sum, i);
}
}
if (maxLength == 0) {
return new String[0];
}
String[] ans = new String[maxLength];
System.arraycopy(array, startIndex, ans, 0, maxLength);
return ans;
}
}

举报

相关推荐

0 条评论