同事刷题:
给定一个元素,类型为小写字符串数组, 请计算两个没有相同字符的子数组的长度乘积的最大值, 若果没有符合条件的子数组, 返回0.
输入条件: 输入为半角逗号分隔的小写字符串数组, 数组长度[2,100], 字符串长度[0,50]
#!/usr/bin/env python3
import re
arr=[]
arr = input('Enter the str: ')
# get between [2,100] num of lowcase chars splittd with','
while 1:
if ((2<=len(arr)<=100) and not re.match(r'.*[^a-z,]+', arr)):
if (re.match(r'.*[a-z]{2}', arr) or re.match(r'.*,,', arr)):
arr = input('1: Re-enter the str into the array: ')
else:
break
else:
arr = input('2: Re-enter the str into the array: ')
strip_arr = arr.replace(',', '')
print(strip_arr)
# get all sub-string from a given string
all_subs = [strip_arr[i: j] for i in range(len(strip_arr)) for j in range(i + 1, len(strip_arr) + 1)]
# judge if have intersection
def inter(a,b):
return list(set(a)&set(b))
max_num=0
for i in all_subs:
for j in all_subs:
if not inter(i,j):
tmp_num = len(i)*len(j)
if (max_num < tmp_num):
max_num = tmp_num
print("The max num is %d"% max_num)
输出:
[~]$ ./test.py
Enter the str: 1
2: Re-enter the str into the array: a
2: Re-enter the str into the array: a,M
2: Re-enter the str into the array: ab,c
1: Re-enter the str into the array: a,,c,d
1: Re-enter the str into the array: a,.d,g
2: Re-enter the str into the array: a,c,t,h,h,f,y,k,q,y,y,u,i,g,k,s,k,l,s,a,h,
acthhfykqyyuigksklsah
The max num is 78
[~]$ ./test.py
Enter the str: a,c,t,h,h,f,y,k,q,y,y,u,i,g,k,s,k,l,s,a,h,f,h,j,u,a,t,i,o,p,x,n,h,k,l,w,h
acthhfykqyyuigksklsahfhjuatiopxnhklwh
The max num is 112