美文网首页
【算法题】面试题 17.05. 字母与数字

【算法题】面试题 17.05. 字母与数字

作者: 程序员小2 | 来源:发表于2023-03-10 17:47 被阅读0次

    题目:

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

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

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

    java代码:

    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;
        }
    }
    
    

    相关文章

      网友评论

          本文标题:【算法题】面试题 17.05. 字母与数字

          本文链接:https://www.haomeiwen.com/subject/uwdtrdtx.html