华为OD机试-求满足要求的最长子串

 题目描述

给定一个字符串,只包含字母和数字,按要求找出字符串中的最长(连续)子串的长度,字符串本身是其最长的子串,子串要求:
1、只包含1个字母(a-z,A~Z),其余必须是数字;
2、字母可以在子串中的任意位置;
如果找不到满足要求的子串,如全是字母或全是数字,则返回-1。

输入描述

字符串(只包含字母和数字)

输出描述

子串的长度

示例一

输入

abC124ACb

输出

4

代码实现

# coding:utf-8

import sys

try:
    while True:
        line = sys.stdin.readline().strip()
        ans = 0
        index = 0
        sl = len(line)
        count = 0
        if line == '':
            break

        for index in range(sl):
            if line[index-1].isalpha() and line[index].isdigit():
                count = 2
                ans = max(ans, count)
            elif count > 0 and line[index].isdigit():
                count += 1
                ans = max(ans, count)
        if ans == 0:
            print(-1)
        else:
            print(f'ans:{ans}')


except Exception as e:
    print(e)

猜你喜欢

转载自blog.csdn.net/SD_JZZ/article/details/132666693