给定一个字符串,只包含字母和数字,按要求找出字符串中的最长(连续)子串的长度,字符串本身是其最长的子串,子串要求:
1、 只包含1个字母(a~z, A~Z),其余必须是数字;
2、 字母可以在子串中的任意位置;
如果找不到满足要求的子串,如全是字母或全是数字,则返回-1。
字符串(只包含字母和数字)
子串的长度
示例1输入输出示例仅供调试,后台判题数据一般不包含示例
abC124ACb
4
满足条件的最长子串是C124或者124A,长度都是4
示例2输入输出示例仅供调试,后台判题数据一般不包含示例
a5
2
字符串自身就是满足条件的子串,长度为2
示例3输入输出示例仅供调试,后台判题数据一般不包含示例
aBB9
2
满足条件的子串为B9,长度为2
示例4输入输出示例仅供调试,后台判题数据一般不包含示例
abcdef
-1
没有满足要求的子串,返回-1
668
+---+
3 | | ++ + +---|
| | | 3 + 6 + | + | +
| + | | + + + | + | +
| + | +---+ + + +++++ + | + | +
| + | + | + +----+ | | + | + | +
| + 3 | + | + + + 2 | | 2 + | + | +
| + | + | + + + | | + | + | +
| +---+ | | | | + ----+ | +---+ | | + | +
| | | | | | + | | | | | | + | +
| 1 | | | 8 | | + 1 | | | 1 | | 1 | | + | +
| | | | | | + | | | | | | | + | +
| +---+ | +---+ | ++---+ ++ +---+ +---+ | + | +
| | | | | | ++ | | |+ | +
|0 | | | 0 | 0 | ++ | 0 | |+ | +
| | | | | | ++ | | |+ | +
+---+ + +-------+ +---+| +|+ | +
+ + | +
0 1 2 3 4 5 6 7 8 9 10 11 12 + v: w u m u 1 0 2 4
按题目逻辑去实现即可,判断好数字、字母就行
def test(ss, pos, end):
cnt1 = 0
cnt2 = 0
begin = pos
end += pos
while pos < end:
if pos >= len(ss):
break
if ss[pos].isdigit():
cnt1 += 1
elif ss[pos].isalpha():
cnt2 += 1
pos += 1
return cnt1 + cnt2 == end - begin and cnt2 == 1 and cnt1 != 0
def main():
ss = input()
for window in range(len(ss), 0, -1):
for i in range(len(ss)):
if test(ss, i, window):
return window
return -1
if __name__ == '__main__':
print(main())