public class Samestring { //thought two: Each character corresponds to its own ASC code, the first idea of the algorithm complexity is O (NLOGN). Can generally use space to reduce the complexity of time//can open a size of 256 array space, and 256 array elements are set to 0, and then traverse the first string to the character's ASC as an array subscript. Array elements are added 1,//and then the second string is traversed to subtract the values of the array elements by 1, assuming that the value of the last array element is 0, the same string. The time complexity of this algorithm is O (n) public static void compare (String s1,string s2) {byte[] b1=s1.getbytes (); byte[] B2=s2.getbytes (); int[] Bcount=new int[256];for (int i=0;i<256;i++) {bcount[i]=0;} for (int i=0;i<b1.length;i++) {bcount[b1[i]-' 0 ']++;} for (int i=0;i<b2.length;i++) {bcount[b2[i]-' 0 ']--;} for (int i=0;i<256;i++) if (bcount[i]!=0) {System.out.println ("not equal!"); return;} System.out.println ("equal!");} public static void Main (string args[]) {string s1= "AAABBBCCC"; String s2= "ABABACBCC"; compare (s1, S2); String s3= "AABBCCDD"; String s4= "abc"; compare (S3, S4);}}
Results: Equalnot Equal
Copyright notice: This article blog original article. Blogs, without consent, may not be reproduced.
Java program Ape's written interview String3