用递归的方法算出给定字符串的最大连续重复字符的重复次数

本文介绍了一种使用递归算法来寻找给定字符串中最大连续重复字符及其重复次数的方法,并提供了具体的Java实现代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1 package com.yan.test01;
 2 
 3 public class LongestSubString {
 4 
 5     // 用递归的方法算出给定字符串的最大连续重复字符的重复次数
 6     public LongestSubString() {
 7     }
 8 
 9     public static int maxLength(String str, int position, int count, int maxLength) {
10 
11         if (position == str.length()) {
12             return maxLength;
13         }
14         if (str.charAt(position) == str.charAt(position - 1)) {
15             count++;
16             if (count > maxLength) {
17                 maxLength = count;
18             }
19         } else {
20             count = 1;
21         }
22         return maxLength(str, position + 1, count, maxLength);
23     }
24 
25     public static void main(String[] args) {
26         // input : "abdsdxxxhbbbbbasdaaf"
27         String str = "abdsdxxxhbbbbbasdaaf"; // "bbbbb"----5
28         // String str = "a"; expected output: 1
29         // String str = ""; expected output: 0
30         // String str = null; expected output: 0
31         if (str == null || str.isEmpty()) {
32             System.out.println(0);
33         } else if (str.length() == 1) {
34             System.out.println(1);
35         } else {
36             System.out.println(maxLength(str, 1, 1, 1));
37         }
38 
39     }
40 
41 }

 

转载于:https://www.cnblogs.com/yanspecial/p/5290987.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值