@@ -66,32 +66,28 @@ public static HashSet<string> ComputeDistinct(string Source)
66
66
/// <summary>
67
67
/// Determines if the Other string is an anargram of the Source string.
68
68
/// </summary>
69
- public static bool IsAnargram ( string Source , string Other )
69
+ public static bool IsAnargram ( string source , string other )
70
70
{
71
- if ( string . IsNullOrEmpty ( Source ) || string . IsNullOrEmpty ( Other ) )
71
+ if ( string . IsNullOrEmpty ( source ) || string . IsNullOrEmpty ( other ) )
72
72
return false ;
73
- else if ( Source . Length != Other . Length )
73
+ else if ( source . Length != other . Length )
74
74
return false ;
75
- else if ( Source == Other )
75
+ else if ( source . Equals ( other , StringComparison . Ordinal ) )
76
76
return true ;
77
77
78
- // Begin the Anagram check
79
- // Covnert strings to character arrays
80
- // O(N) space complexity
81
- var sourceCharArray = Source . ToCharArray ( ) ;
82
- var otherCharArray = Other . ToCharArray ( ) ;
83
-
84
- // Sort both character arrays in place using heapsort
85
- // O(N log N) operation
86
- sourceCharArray . HeapSort < char > ( Comparer < char > . Default ) ;
87
- otherCharArray . HeapSort < char > ( Comparer < char > . Default ) ;
88
-
89
- // One pass scan
90
- // O(N) operation
91
- for ( int i = 0 ; i < sourceCharArray . Length ; ++ i )
92
- if ( sourceCharArray [ i ] != otherCharArray [ i ] )
93
- return false ;
94
-
78
+ int len = source . Length ;
79
+ // Hash set which will contains all the characters present in input souce.
80
+ var hashSetSourceChars = new HashSet < char > ( ) ;
81
+ for ( int i = 0 ; i < len ; i ++ )
82
+ {
83
+ hashSetSourceChars . Add ( source [ i ] ) ;
84
+ }
85
+ for ( int i = 0 ; i < len ; i ++ )
86
+ {
87
+ // Inputs are not Anargram if characers from *other are not present in *source.
88
+ if ( ! hashSetSourceChars . Contains ( other [ i ] ) ) return false ;
89
+ //if (!hashSetOther.Contains(source[i])) return false;
90
+ }
95
91
return true ;
96
92
}
97
93
}
0 commit comments