Minimum adjacent swaps to group similar characters together | Java program for the above approach ; Function to find minimum adjacent swaps required to make all the same character adjacent ; Initialize answer ; Create a 2D array of size 26 ; Traverse the String ; Get character ; Append the current index in the corresponding vector ; Traverse each character from a to z ; Add difference of adjacent index ; Return answer ; Driver Code ; Given String ; Size of String ; Function Call
import java . util . * ; class GFG { static int minSwaps ( String S , int n ) { int swaps = 0 ; @ SuppressWarnings ( " unchecked " ) Vector < Integer > [ ] arr = new Vector [ 26 ] ; for ( int i = 0 ; i < arr . length ; i ++ ) arr [ i ] = new Vector < Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int pos = S . charAt ( i ) - ' a ' ; arr [ pos ] . add ( i ) ; } for ( char ch = ' a ' ; ch <= ' z ' ; ++ ch ) { int pos = ch - ' a ' ; for ( int i = 1 ; i < arr [ pos ] . size ( ) ; ++ i ) { swaps += Math . abs ( arr [ pos ] . get ( i ) - arr [ pos ] . get ( i - 1 ) - 1 ) ; } } return swaps ; } public static void main ( String [ ] args ) { String S = " abbccabbcc " ; int N = S . length ( ) ; System . out . print ( minSwaps ( S , N ) ) ; } }