We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
classResult{publicstaticfinalintNUM_LETTERS=26;/* * Complete the 'alternate' function below. * * The function is expected to return an INTEGER. * The function accepts STRING s as parameter. */publicstaticintalternate(Strings){// Edge case: if length <= 1, no alternations are possibleif(s.length()<=1){System.out.println(0);return0;}// Flattened array to represent the upper triangular portion of the matrixint[]count=newint[(NUM_LETTERS*(NUM_LETTERS-1))/2];char[]lastSeen=newchar[(NUM_LETTERS*(NUM_LETTERS-1))/2];// Helper function to calculate the index in the flattened array// Process the stringfor(charc:s.toCharArray()){intcharIndex=c-'a';// Update all pairs involving this characterfor(inti=0;i<NUM_LETTERS;i++){if(i==charIndex)continue;intindex=charIndex<i?getIndex(charIndex,i):getIndex(i,charIndex);if(count[index]!=-1){// Only process if validif(lastSeen[index]==c){count[index]=-1;// Invalidate if repeating}else{lastSeen[index]=c;// Update last seen charactercount[index]++;}}}}// Find the maximum valid countintmax=0;for(intc:count){max=Math.max(max,c);}returnmax;}privatestaticintgetIndex(inti,intj){returni*NUM_LETTERS+j-((i+1)*(i+2))/2;}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Two Characters
You are viewing a single comment's thread. Return to all comments →
Java solution using a 1D array matrix