美文网首页
最长的指定瑕疵度的元音字串

最长的指定瑕疵度的元音字串

作者: 抬头挺胸才算活着 | 来源:发表于2021-09-19 21:49 被阅读0次

· “a” 、 “aa”是元音字符串,其瑕疵度都为0
· “aiur”不是元音字符串(结尾不是元音字符)
· “abira”是元音字符串,其瑕疵度为2

给定一个字符串,请找出指定瑕疵度的最长元音字符子串,并输出其长度,如果找不到满足条件的元音字符子串,输出0。
子串:字符串中任意个连续的字符组成的子序列称为该字符串的子串。
输入描述:
首行输入是一个整数,表示预期的瑕疵度flaw,取值范围[0, 65535]。
接下来一行是一个仅由字符a-z和A-Z组成的字符串,字符串长度(0, 65535]。
输出描述:
输出为一个整数,代表满足条件的元音字符子串的长度。
示例1
输入
0
asdbuiodevauufgh
输出
3
说明
满足条件的最长元音字符子串有两个,分别为uio和auu,长度为3。
示例2
输入
2
aeueo
输出
0
说明
没有满足条件的元音字符子串,输出0
示例3
输入
1
aabeebuu
输出
5
说明
满足条件的最长元音字符子串有两个,分别为aabee和eebuu,长度为5

public class OJ1794 {
    private static HashSet<Character> vowels = new HashSet<>(
        Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'));

    /**
     * main入口由OJ平台调用
     */
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in, StandardCharsets.UTF_8.name());
        int flaw = Integer.parseInt(cin.nextLine());
        String input = cin.nextLine();
        cin.close();

        System.out.println(getLongestFlawedVowelSubstrLen(flaw, input));
    }

    // 待实现函数,在此函数中填入答题代码
    private static int getLongestFlawedVowelSubstrLen(int flaw, String input) {
        int left = 0;
        int right = -1;
        int currentFlaw = 0;
        int max = 0;

        while (right < input.length() - 1) {
            right += 1;
            if (!isVowel(input.charAt(right))) {
                currentFlaw += 1;
            }

            while (currentFlaw > flaw) {
                if (!isVowel(input.charAt(left))) {
                    currentFlaw -= 1;
                }
                // 这步会提前到达下一个点,可能会超范围
                left += 1;
            }

            if (left < input.length() && currentFlaw == flaw && isVowel(input.charAt(left)) && isVowel(
                input.charAt(right))) {
                max = Math.max(max, right + 1 - left);
            }
        }

        return max;
    }

    private static boolean isVowel(char c) {
        return vowels.contains(c);
    }
}

相关文章

网友评论

      本文标题:最长的指定瑕疵度的元音字串

      本文链接:https://www.haomeiwen.com/subject/aubpgltx.html