1年前 (2018-08-14) |   抢沙发  7

One word is an anagram of another word if it is a rearrangement of all the letters of the second word. For example, the character arrays {‘s’, ‘i’, ‘t’} and {‘i’, ‘t’, ‘s’} represent words that are anagrams of one another because “its” is a rearrangement of all the letters of “sit” and vice versa. Write a function that accepts two character arrays and returns 1 if they are anagrams of one another, otherwise it returns 0. For simplicity, if the two input character arrays are equal, you may consider them to be anagrams.
If you are programming in Java or C#, the function signature is:
int areAnagrams(char [ ] a1, char [ ] a2)
If you are programming in C or C++, the function signature is
int areAnagrams(a1 char[ ], a2 char[ ], int len) where len is the length of a1 and a2.
Hint: Please note that “pool” is not an anagram of “poll” even though they use the same letters. Please be sure that your function returns 0 if given these two words! You can use another array to keep track of each letter that is found so that you don’t count the same letter twice (e.g., the attempt to find the second “o” of “pool” in “poll” should fail.)
Hint: do not modify either a1 or a2, i.e., your function should have no side effects! If your algorithm requires modification of either of these arrays, you must work with a copy of the array and modify the copy!

java 代码实现：

```package com.zzy;

/**
* Created by hadoopall on 13/08/2018.
*/
public class Anagrams {
public static void main(String[] args) {

//        char[] a1 = {'s','i','t'};
//        char[] a2 = {'i','t','s'};

//        char[] a1 = {'s','i','t'};
//        char[] a2 = {'i','d','s'};

//        char[] a1 = {'b','i','g'};
//        char[] a2 = {'b','i','t'};

//        char[] a1 = {'b','o','g'};
//        char[] a2 = {'b','o','o'};

//        char[] a1 = {};
//        char[] a2 = {};
//
//        char[] a1 = {'b','i','g'};
//        char[] a2 = {'b','i','g'};
//
char[] a1 = {'p','o','o','l'};
char[] a2 = {'p','o','l','l'};

System.out.println(areAnagrams(a1,a2));

}
public static  int areAnagrams(char[]a1, char[]a2){

if(a1.length != a2.length){
return 0;
}
int[] temp = new int[a1.length];

for (int i = 0; i &lt; a1.length; i++) {
int count = 0;

for (int j = 0; j &lt; a2.length; j++) {
if(a1[i] == a2[j]){
//                    temp[i] =1;
count ++;

}
temp[i] =  count;

}

}

for (int i = 0; i &lt; temp.length; i++) {
if(temp[i] == 0){
return 0; // 有元素不存在
} else if(temp[i] &gt; 1){

if(findArray(a1,a1[i]) != temp[i]){
return 0;
}

}
}
return 1;
}

public static  int findArray(char[] a, char n){
int count = 0;

for (int i = 0; i &lt; a.length; i++) {
if(a[i] == n){
count ++;

}
}
return count;

}

}
``` ### 注册 