题目
难度中等153
给定一个放有字母和数字的数组,找到最长的子数组,且包含的字母和数字的个数相同。
返回该子数组,若存在多个最长子数组,返回左端点下标值最小的子数组。若不存在这样的数组,返回一个空数组。
示例 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
来源:LeetCode(力扣)
思路
遍历整个数组得到字母的个数和数字的个数,最长的肯定是和两倍的数字和字母之中最小个数相等,如果其中有一个为0则返回空数组
解题
class Solution {
public static boolean isInteger(String str) {
Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
return pattern.matcher(str).matches();
}
public String[] findLongestSubarray(String[] array) {
int num = 0;
int abc = 0;
//遍历数组,获取字母和数字的个数
for (int i = 0; i < array.length; i++) {
if (isInteger(array[i])) {
num ++;
} else {
abc ++;
}
}
System.out.println(num);
System.out.println(abc);
//存在为0的则返回空数组
if(num ==0 || abc == 0){
String[] strings = new String[0];
return strings;
}
//返回的数组长度
int l = Math.min(abc,num) * 2;
String[] s = new String[l];
//滑动窗口
//内部相同即可
for (int i = 0; i < array.length - l + 1; i++) {
int num1 = 0;
int abc1 = 0;
for (int j = 0; j < l; j++) {
s[j] = array[i + j];
if (isInteger(s[j])) {
num1 ++;
}
}
if (num1 == l /2){
break;
}
}
return s;
}
}
想错了。。。
看了解答了解了一点前缀和知识和判断字母数字的方法
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;
}
}
//判断是否是字母可以用>="A"
总结
还是太菜,多多学习
标签:String,230311,int,每日,++,算法,数组,maxLength,array From: https://www.cnblogs.com/tyrantblue/p/17207341.html