[字符串算法题]2.判断两个字符串是否由相同的字符组成

时间:2021-12-01 22:16:16

问题:判断两个字符串是否由相同的字符组成。如输入:abc cba,输出:true。

1.排序法,代码如下:

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s1 = scanner.next();
String s2 = scanner.next();
System.out.println(isStringEqual(s1, s2));
}

public static boolean isStringEqual(String s1, String s2) {
if(s1.length() != s2.length()) {
return false;
}
//将两个字符串分别转化为字节数组bytes1、bytes2
byte[] bytes1 = s1.getBytes();
byte[] bytes2 = s2.getBytes();
//对数组进行排序
Arrays.sort(bytes1);
Arrays.sort(bytes2);
for(int i = 0; i < bytes1.length; i++) {
if(bytes1[i] != bytes2[i]) {
return false;
}
}
return true;
}

2.空间换时间。对于字符串1出现的字符,数组加1,字符串2出现的字符,数组减1。最后遍历整个数组,值是否都为0。出现不为0的直接返回false。

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s1 = scanner.next();
String s2 = scanner.next();
System.out.println(isStringEqual(s1, s2));
}

public static boolean isStringEqual(String s1, String s2) {
if (s1.length() != s2.length()) {
return false;
}
//将两个字符串分别转化为字节数组bytes1、bytes2
byte[] bytes1 = s1.getBytes();
byte[] bytes2 = s2.getBytes();
int[] charCount = new int[256];
for (int i = 0; i < bytes1.length; i++) {
//对于字符串1出现的字符,数组加1,字符串2出现的字符,数组减1
charCount[bytes1[i]]++;
charCount[bytes2[i]]--;
}
for (int i = 0; i < charCount.length; i++) {
if (charCount[i] != 0) {
return false;
}
}
return true;
}