Java面试题算法篇寻找字符串中最长的重复元素子串

package com.puhui.goosecard.web.utils;
 
// Java program to find the maximum consecutive
// repeating character in given string
class GFG {
 
    // function to find out the maximum repeating
	// character in given string
	static void maxRepeating(String str)
	{
		char[] array = str.toCharArray();
		int count = 1;
		int max = 0;
		char maxChar = 0;
		int maxIndex=0;
		for(int i=1; i<array.length; i++){ // Start from 1 since we want to compare it with the char in index 0
			if(array[i]==array[i-1]){
				count++;
			} else {
				if(count>max){  // Record current run length, is it the maximum?
					max=count;
					maxChar=array[i-1];
					maxIndex=i-1;
				}
				count = 1; // Reset the count
			}
		}
		if(count>max){
			max=count; // This is to account for the last run
			maxChar=array[array.length-1];
			maxIndex=array.length-1;
		}
		System.out.println("Longest run: "+max+", for the character "+maxChar+"and the max char index is:"+maxIndex);
		System.out.println(str.substring(maxIndex-(max-1),maxIndex+1));
 
	}
 
	// Driver code
	public static void main(String args[])
	{
		String str = "ssstrtyweweqqqqqookkpppdddddddsaw";
		maxRepeating(str);
	}
}
 
// This code is contributed by Sudeep Mukherjee

 

    原文作者:hanruikai
    原文地址: https://blog.csdn.net/hanruikai/article/details/81505862
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞