finding if two words are anagrams of each other

后端 未结 22 1221
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 14:51

I am looking for a method to find if two strings are anagrams of one another.

Ex: string1 - abcde
string2 - abced
Ans = true
Ex: string1 - abcde
string2 - ab         


        
22条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 15:08

    If both strings are of equal length proceed, if not then the strings are not anagrams.

    Iterate each string while summing the ordinals of each character. If the sums are equal then the strings are anagrams.

    Example:

        public Boolean AreAnagrams(String inOne, String inTwo) {
    
            bool result = false;
    
            if(inOne.Length == inTwo.Length) {
    
                int sumOne = 0;
                int sumTwo = 0;
    
                for(int i = 0; i < inOne.Length; i++) {
    
                    sumOne += (int)inOne[i];
                    sumTwo += (int)inTwo[i];
                }
    
                result = sumOne == sumTwo;
            }
    
            return result;
        }
    

提交回复
热议问题