题目:
给定一个放有字母和数字的数组,找到最长的子数组,且包含的字母和数字的个数相同。
返回该子数组,若存在多个最长子数组,返回左端点下标值最小的子数组。若不存在这样的数组,返回一个空数组。
示例 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 indices = new HashMap();
indices.put(0, -1);
int sum = 0;
int maxLength = 0;
int startIndex = -1;
int n = array.length;
for (int i = 0; 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;
}
}
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
机房租用,北京机房租用,IDC机房托管, http://www.e1idc.net