题目浅析

  • 想查看原题可以点击目链接

  • 简单地说,就是给一个数组,由字母和数字组成,找出其中字母和数字数目相同的子数组中,长度最长的那个。

思路分享

代码解答(强烈建议自行解答后再看)

  • 参考题解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
def findLongestSubarray(self, array: List[str]) -> List[str]:
acc_sum = 0
rec = defaultdict(int)
max_len = 0
max_index = 0
rec[0] = -1

for i, x in enumerate(array):
acc_sum += 1 if x.isdigit() else -1

if acc_sum in rec:
acc_len = i - rec[acc_sum]
if max_len < acc_len:
max_len = acc_len
max_index = rec[acc_sum]
else:
rec[acc_sum] = i

max_index += 1
return array[max_index:max_index+max_len]