Count the nodes of a tree whose weighted string does not contain any duplicate characters | Java implementation of the approach ; Function that returns true if the String contains unique characters ; Function to perform dfs ; If weighted String of the current node contains unique characters ; Driver code ; Weights of the nodes ; Edges of the tree
import java . util . * ; class GFG { static int cnt = 0 ; static Vector < Integer > [ ] graph = new Vector [ 100 ] ; static String [ ] weight = new String [ 100 ] ; static boolean uniqueChars ( char [ ] arr ) { HashMap < Character , Integer > mp = new HashMap < Character , Integer > ( ) ; int n = arr . length ; for ( int i = 0 ; i < n ; i ++ ) if ( mp . containsKey ( arr [ i ] ) ) { mp . put ( arr [ i ] , mp . get ( arr [ i ] ) + 1 ) ; } else { mp . put ( arr [ i ] , 1 ) ; } if ( mp . size ( ) == arr . length ) return true ; else return false ; } static void dfs ( int node , int parent ) { if ( uniqueChars ( weight [ node ] . toCharArray ( ) ) ) cnt += 1 ; for ( int to : graph [ node ] ) { if ( to == parent ) continue ; dfs ( to , node ) ; } } public static void main ( String [ ] args ) { for ( int i = 0 ; i < 100 ; i ++ ) graph [ i ] = new Vector < Integer > ( ) ; weight [ 1 ] = " abc " ; weight [ 2 ] = " aba " ; weight [ 3 ] = " bcb " ; weight [ 4 ] = " moh " ; weight [ 5 ] = " aa " ; graph [ 1 ] . add ( 2 ) ; graph [ 2 ] . add ( 3 ) ; graph [ 2 ] . add ( 4 ) ; graph [ 1 ] . add ( 5 ) ; dfs ( 1 , 1 ) ; System . out . print ( cnt ) ; } }