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 }