Java面試題演算法篇尋找字串中最長的重複元素子串
阿新 • • 發佈:2019-01-10
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