这里利用了map集合,思路是将第一个字符串的字母都放入map中
然后遍历第二个字符串,试图将所有字母从map中取出
最后判断map是否为空即可
import java.util.*; public class Client { public static void main(String[] args) { String str = "abc"; String other = "baac"; boolean same = isSame(str, other); System.out.println(same); } static boolean isSame(String str, String other) { Map<Character, Integer> map = new HashMap<>(); for (char c : str.toCharArray()) { Integer integer = map.get(c); if (integer == null) { map.put(c, 1); } else { map.put(c, integer + 1); } } for (char c : other.toCharArray()) { Integer integer = map.get(c); if (integer == null) { return false; } else { int newVal = integer - 1; if (newVal <= 0) { map.remove(c); } else { map.put(c, newVal); } } } return map.isEmpty(); } }