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; imax){  // 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

 

你可能感兴趣的:(面试题,java常见知识)