找出字符串中最长的连续元音子串长度

给定一个由小写字母组成的字符串,找出其中最长的连续元音子串的长度。元音字母包括 'a'、'e'、'i'、'o'、'u'。

例如,在字符串 'leetcode' 中,最长的连续元音子串是 'e',长度为 1;在字符串 'aeiou' 中,最长的连续元音子串是整个字符串,长度为 5。

解法一:

遍历字符串,使用一个计数器记录当前连续元音的长度,同时记录最长的连续元音长度,当遇到非元音字母时,将计数器归零。

时间复杂度:O(n)

空间复杂度:O(1)

Python 代码

class Solution:
    def findLongestSubstring(self, s: str) -> int:
        vowels = {'a', 'e', 'i', 'o', 'u'}
        max_len = 0
        cur_len = 0
        for c in s:
            if c in vowels:
                cur_len += 1
                max_len = max(max_len, cur_len)
            else:
                cur_len = 0
        return max_len

解法二:

使用正则表达式匹配所有连续的元音子串,找出其中最长的子串。

时间复杂度:O(n)

空间复杂度:O(1)

Python 代码

import re

class Solution:
    def findLongestSubstring(self, s: str) -> int:
        matches = re.findall(r'[aeiou]+', s)
        if matches:
            return max(len(match) for match in matches)
        else:
            return 0
找出字符串中最长的连续元音子串长度

原文地址: https://www.cveoy.top/t/topic/m5X6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录