How to tell if two strings are made up of the same characters
Title Description:
The same character consists of the letters that make up two strings, and the number of letters is the same, except that they are arranged in a different order. For example, "AAAABBC" and "abcbaaa" are made up of the same characters.
Method One:
Sort by sorting the characters in two strings, comparing the two sorted strings for equality. If they are equal, they are made up of the same characters, otherwise they are made up of different characters.
Import Java.util.Arrays; Public classSolution { Public Static void Compare(String s1,string S2) {byte[] B1 = S1.getbytes ();byte[] B2 = S2.getbytes (); Arrays.sort (B1); Arrays.sort (B2); S1 =NewString (B1); S2 =NewString (B2);if(S1.equals (S2)) {System. out. println ("Equal"); }Else{System. out. println ("Not Equal"); } } Public Static void Main(string[] args) {String S1 ="AAAABBC"; String s2 ="ABCBAAA"; Compare (S1, S2); S1 ="AAAABBC"; S2 ="Abcbaab"; Compare (S1, S2); }}
The above method depends on the time complexity of the sorting algorithm, because the time complexity of the quickest sorting algorithm is O (NLOGN), so the time complexity of the method is also O (NLOGN).
Method Two:
Space-time, assuming that the string only uses Ascaii characters, because the Ascaii character only 266 (corresponding to the encoding of 0~255), in the implementation can be requested by the size of 266 array to record the number of occurrences of each character, and initialized to 0, and then traverse the first string, The ASCII value corresponding to the character in the string is subscript as an array, the element of the corresponding array is added 1, and then the second string is traversed, The value of the corresponding element in the array-1. If the value of each element in the last array is 0, the two strings are made up of the same characters; otherwise, the two strings are made up of different characters.
The code is as follows:
The package determines whether two strings are composed of the same characters; Public classSolution1 { Public Static void Compare(string s1, string s2) {byte[] B1 = S1.getbytes ();byte[] B2 = S2.getbytes ();int[] Bcount =New int[ the]; for(inti =0; I < the; i++) {Bcount[i] =0; } for(inti =0; i < b1.length; i++) {Bcount[b1[i]-' 0 ']++; } for(inti =0; i < b2.length; i++) {Bcount[b2[i]-' 0 ']--; } for(inti =0; I < the; i++) {if(Bcount[i]! =0) {System. out. println ("Not Equal");return; }} System. out. println ("Equal"); } Public Static void Main(string[] args) {String S1 ="AAAABBC"; String s2 ="ABCBAAA"; Compare (S1, S2); S1 ="AAAABBC"; S2 ="Abcbaab"; Compare (S1, S2); }}
The two-time complexity of the method is O (n), but additional space is applied.
[algorithm] Determines whether two strings are made up of the same characters