An instance of Java that determines whether two strings are composed of the same characters

Problem: composed of the same characters means that two strings have the same letters and the number of letters, but in different order. For example, "aaaabbc" and "abcbaaa" are composed of the same characters.

Method 1: sorting method is also the easiest way to think of. Convert two strings into byte arrays, sort them respectively, and judge whether they are the same.

Method 2: set method (space for time), using the uniqueness of the key of the map set, traverse the first string, taking the character as the key, the number of occurrences of the character as the value, and if a duplicate character is encountered, value + 1. Then traverse the second string, and if a character is encountered, the corresponding value-1 will be. If the value value is 1, the character will be removed. Finally, judge whether the map is empty. If it is empty, it indicates two characters The string is the same.

Method 3: array method (space for time): since there are 266 ASCII characters in total, apply for a byte array byte [256], initialize it to 0, then traverse the first string, add the corresponding ASCII subscript + 1, and then traverse the second string, and add the corresponding subscript - 1. If the values of each element in the last array are 0, it means that the strings are equal, and vice versa.

First, the source code of method 2 and method 3 is given:

To test the running time of the two methods, construct a larger string, and the running results are as follows:

It can be seen that the array method is more efficient. If there is no space requirement, the third method is recommended.

The above example of Java judging whether two strings are composed of the same characters is all the content shared by Xiaobian. I hope it can give you a reference and support more programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>