text: Check if a string has all characters with same frequency with one variation allowed | C # program to check if a string can be made valid by removing at most 1 character using hashmap . ; To check a string S can be converted to a variation string ; Run loop form 0 to length of string ; declaration of variables ; if first is true than countOfVal1 increase ; if second is true than countOfVal2 increase ; Driver code
code: using System ; using System . Collections . Generic ; public class AllCharsWithSameFrequencyWithOneVarAllowed { public static bool checkForVariation ( String str ) { if ( str == null str . Length != 0 ) { return true ; } Dictionary < char , int > map = new Dictionary < char , int > ( ) ; for ( int i = 0 ; i < str . Length ; i ++ ) { if ( map . ContainsKey ( str [ i ] ) ) map [ str [ i ] ] = map [ str [ i ] ] + 1 ; else map . Add ( str [ i ] , 1 ) ; } bool first = true , second = true ; int val1 = 0 , val2 = 0 ; int countOfVal1 = 0 , countOfVal2 = 0 ; foreach ( KeyValuePair < char , int > itr in map ) { int i = itr . Key ; if ( first ) { val1 = i ; first = false ; countOfVal1 ++ ; continue ; } if ( i == val1 ) { countOfVal1 ++ ; continue ; } if ( second ) { val2 = i ; countOfVal2 ++ ; second = false ; continue ; } if ( i == val2 ) { countOfVal2 ++ ; continue ; } return false ; } if ( countOfVal1 > 1 && countOfVal2 > 1 ) { return false ; } else { return true ; } } public static void Main ( String [ ] args ) { Console . WriteLine ( checkForVariation ( " abcbc " ) ) ; } }