题目
给定两个字符串 s1 和 s2,请编写一个程序,确定其中一个字符串的字符重新排列后,能否变成另一个字符串。
示例1:
输入: s1 = "abc", s2 = "bca"
输出: true
示例2:
输入: s1 = "abc", s2 = "bad"
输出: false
说明:
0 <= len(s1) <= 100
0 <= len(s2) <= 100
思路一
首先判断两个字符串是否长度一致,不一致返回false。
利用map结构存储第一个字符串的字符统计数据。
然后遍历第二个字符串,如果map中不包含该字符,返回false,包含则count减1。
private static boolean CheckPermutation(String s1, String s2) {
Map<Character, Integer> map = new HashMap<>();
if (s1.length() != s2.length())
return false;
for (int i = 0; i < s1.length(); i++) {
char ch = s1.charAt(i);
map.put(ch, map.containsKey(ch) ? map.get(ch) + 1 : 1);
}
for (int i = 0; i < s2.length(); i++) {
char ch = s2.charAt(i);
if (!map.containsKey(ch))
return false;
int count = map.get(ch);
if (count == 1){
map.remove(ch);
}
else {
map.put(ch, count - 1);
}
}
if (map.size() > 0)
return false;
return true;
}
思路二
将两个字符串转换为字符数组进行排序,再转化为字符串看两个字符串是否相等。、
private static boolean CheckPermutation1(String s1, String s2) {
char[] ch1 = s1.toCharArray();
Arrays.sort(ch1);
char[] ch2 = s2.toCharArray();
Arrays.sort(ch2);
return new String(ch1).equals(new String(ch2));
}