Java 字符串子串计数:包含 'r' 和 'e',但不包含 'd'

本文将介绍如何使用 Java 代码计算给定字符串中包含 'r' 和 'e',但不包含 'd' 的连续子串数量。

代码示例

public class Main {
    public static void main(String[] args) {
        String input = "redrere";
        int count = countSubstrings(input);
        System.out.println("连续子串包含'r'和'e',但不包含'd'的数量为:" + count);
    }
    
    public static int countSubstrings(String input) {
        int count = 0;
        for (int i = 0; i < input.length(); i++) {
            if (input.charAt(i) == 'r') {
                for (int j = i + 1; j < input.length(); j++) {
                    if (input.charAt(j) == 'e') {
                        boolean containsD = false;
                        for (int k = i + 1; k < j; k++) {
                            if (input.charAt(k) == 'd') {
                                containsD = true;
                                break;
                            }
                        }
                        if (!containsD) {
                            count++;
                        }
                    }
                }
            }
        }
        return count;
    }
}

解释

  1. 循环遍历: 首先,我们使用两个嵌套循环遍历字符串 input 中的每个可能的子串。外层循环负责确定子串的起始位置 i,内层循环负责确定子串的结束位置 j
  2. 判断条件: 对于每个子串,我们检查它是否以 'r' 开头,以 'e' 结尾,并且不包含 'd'。
  3. 计数: 如果满足上述条件,我们将计数器 count 加一。
  4. 返回结果: 最后,函数返回 count 的值,即满足条件的子串数量。

例子

输入字符串为 "redrere",程序将输出:

连续子串包含'r'和'e',但不包含'd'的数量为:3

在这个例子中,满足条件的子串为:

  • "re"
  • "rer"
  • "re"

总结

本示例展示了如何使用 Java 代码解决字符串子串计数问题。通过循环遍历和条件判断,我们可以有效地计算出满足特定条件的子串数量。

Java 字符串子串计数:包含 'r' 和 'e',但不包含 'd'

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

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