Count of distinct permutation of a String obtained by swapping only unequal characters | Importing HashMap class ; Function to calculate total number of valid permutations ; Creating count which is equal to the Total number of characters present and ans that will store the number of unique permutations ; Storing frequency of each character present in the string ; Adding count of characters by excluding characters equal to current char ; Reduce the frequency of the current character and count by 1 , so that it cannot interfere with the calculations of the same elements present to the right of it . ; Return ans + 1 ( Because the given string is also a unique permutation )
import java . util . HashMap ; class GFG { static int validPermutations ( String str ) { HashMap < Character , Integer > m = new HashMap < Character , Integer > ( ) ; int count = str . length ( ) , ans = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { m . put ( str . charAt ( i ) , m . getOrDefault ( str . charAt ( i ) , 0 ) + 1 ) ; } for ( int i = 0 ; i < str . length ( ) ; i ++ ) { ans += count - m . get ( str . charAt ( i ) ) ; m . put ( str . charAt ( i ) , m . get ( str . charAt ( i ) ) - 1 ) ; count -- ; } return ans + 1 ; } public static void main ( String [ ] args ) { String str = " sstt " ; System . out . println ( validPermutations ( str ) ) ; } }