1 import java.util.Arrays; 2 import java.util.Scanner; 3 4 /** 5 * 功能:判断两个字符串是否由相同的字符组成,比如aaaabbc和abcbaaa就是。 6 * 思路1:将两个字符串按字符进行排序,判断排序后字符串是否相同; 7 * 思路2:申请一个256大小的int数组,遍历第一个字符串,遇到一个字符,就将字符对应的数组下标的元素+1,然后,遍历第二个字符串,同理-1,最后,判断数组的所有元素是否都是0. 8 */ 9 public class Main { 10 11 public boolean compare1(String str1, String str2) { 12 13 char[] chars1 = str1.toCharArray(); 14 char[] chars2 = str2.toCharArray(); 15 16 Arrays.sort(chars1); 17 Arrays.sort(chars2); 18 19 return String.valueOf(chars1).equals(String.valueOf(chars2)); 20 } 21 22 public boolean compare2(String str1, String str2) { 23 24 int[] result = new int[256]; 25 char[] chars1 = str1.toCharArray(); 26 char[] chars2 = str2.toCharArray(); 27 28 for (int i = 0; i < chars1.length; i++) { 29 result[chars1[i]]++; 30 } 31 32 for (int i = 0; i < chars2.length; i++) { 33 result[chars2[i]]--; 34 } 35 36 for (int i = 0; i < result.length; i++) { 37 if (result[i] != 0) { 38 return false; 39 } 40 } 41 return true; 42 } 43 44 public static void main(String[] args) { 45 Main main = new Main(); 46 Scanner scanner = new Scanner(System.in); 47 48 while (scanner.hasNextLine()) { 49 String str1 = scanner.nextLine(); 50 String str2 = scanner.nextLine(); 51 52 if (str1 == null || str2 == null) { 53 continue; 54 } 55 56 System.out.println(main.compare1(str1, str2)); 57 System.out.println(main.compare2(str1, str2)); 58 } 59 } 60 }