aiaiask.com©

开花即结果 提问即答案

用Java编写代码:计算给定字符串中"oppo"型子序列的数量(长度为4,首尾为元音,中间为辅音且为回文串)
原始问题:

用Java编写代码:计算给定字符串中"oppo"型子序列的数量(长度为4,首尾为元音,中间为辅音且为回文串)

以下是使用Java编写的解决方案:

public class OppoStringCount {
    public static void main(String[] args) {
        String input = "awwa";
        int count = countOppoStrings(input);
        System.out.println("该字符串中有 " + count + " 个oppo型子序列");
    }

    public static int countOppoStrings(String input) {
        int count = 0;
        int n = input.length();

        for (int i = 0; i < n; i++) {
            for (int j = i + 3; j < n; j++) {
                if (isOppoString(input, i, j)) {
                    count++;
                }
            }
        }

        return count;
    }

    public static boolean isOppoString(String input, int start, int end) {
        if (end - start + 1 != 4) {
            return false;
        }

        char[] vowels = {'a', 'e', 'i', 'o', 'u'};
        char[] consonants = {'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'};

        char first = input.charAt(start);
        char second = input.charAt(start + 1);
        char third = input.charAt(start + 2);
        char fourth = input.charAt(end);

        boolean isFirstVowel = containsChar(vowels, first);
        boolean isSecondConsonant = containsChar(consonants, second);
        boolean isThirdConsonant = containsChar(consonants, third);
        boolean isFourthVowel = containsChar(vowels, fourth);

        return isFirstVowel && isSecondConsonant && isThirdConsonant && isFourthVowel && isPalindrome(input, start, end);
    }

    public static boolean containsChar(char[] arr, char c) {
        for (char ch : arr) {
            if (ch == c) {
                return true;
            }
        }
        return false;
    }

    public static boolean isPalindrome(String input, int start, int end) {
        while (start < end) {
            if (input.charAt(start) != input.charAt(end)) {
                return false;
            }
            start++;
            end--;
        }
        return true;
    }
}

这段代码首先定义了一个countOppoStrings方法,用于计算给定字符串中"oppo"型子序列的数量。该方法通过两层循环遍历字符串的所有可能子序列,并调用isOppoString方法判断是否满足"oppo"型字符串的条件,如果满足则计数器加一。

isOppoString方法用于判断一个子序列是否满足"oppo"型字符串的条件。首先检查子序列的长度是否为4,然后分别判断第一个、第二个、第三个和最后一个字符是否满足元音和辅音的条件,并调用isPalindrome方法判断子序列是否为回文串。

containsChar方法用于判断一个字符是否在给定的字符数组中。

isPalindrome方法用于判断一个子序列是否为回文串,通过比较子序列的首尾字符是否相等来判断。

最后,在main方法中,我们可以调用countOppoStrings方法并传入一个字符串来计算"oppo"型子序列的数量,并输出结果。

用Java编写代码:计算给定字符串中"oppo"型子序列的数量(长度为4,首尾为元音,中间为辅音且为回文串)
https://www.aiaiask.com/ask/45340.html
AI / 模型DeepSeek
时间 / DATEAugust 26, 2023, 5:48 PM
语言zh-CN
IP / 区域陕西 西安