面试题 17.05. 字母与数字

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

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

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

输出: []

1.子区间的问题一般是滑动窗口或者前缀和+hash

注意点:str.isdigit(),条件判断

class Solution:
    def findLongestSubarray(self, array: List[str]) -> List[str]:
        hash_map=collections.defaultdict(list)
        cnt=[]
        char=number=0
        left=right=0
        for a in array:
            if a.isdigit():number+=1
            else:char+=1
            cnt.append([number,char])
        for i in range(len(cnt)):
            if cnt[i][0]==cnt[i][1] and right-left<i:
                left=0
                right=i
            if cnt[i][1]-cnt[i][0] in hash_map and (right-left+1<i-hash_map[cnt[i][1]-cnt[i][0]][0] or (hash_map[cnt[i][1]-cnt[i][0]][0]+1<left and right-left+1==i-hash_map[cnt[i][1]-cnt[i][0]][0] )):
                left=hash_map[cnt[i][1]-cnt[i][0]][0]+1
                right=i
            hash_map[cnt[i][1]-cnt[i][0]].append(i)
        return array[left:right+1] if not left==right==0 else []

 

©️2020 CSDN 皮肤主题: 创作都市 设计师:CSDN官方博客 返回首页