[算法题]判断是否互为字符重排
2020年9月10日
给定两个字符串 s1
和 s2
,请编写一个程序,确定其中一个字符串的字符重新排列后,能否变成另一个字符串。
示例 1:
输入: s1 = "abc", s2 = "bca"
输出: true
示例 2:
输入: s1 = "abc", s2 = "bad"
输出: false
说明:
0 <= len(s1) <= 100
0 <= len(s2) <= 100
思路
利用Set集合不重复的特性,将两字符串分别放入Set中,比较两个Set是否相等即可判断是否可以重排
解答
class Solution {
public boolean CheckPermutation(String s1, String s2) {
Set set1 =new HashSet();
Set set2 =new HashSet();
for(int i=0;i<s1.length();i++){
set1.add(s1.charAt(i));
}
for(int i=0;i<s2.length();i++){
set2.add(s2.charAt(i));
}
if(set1.equals(set2)){
return true;
}else{
return false;
}
}
}
知识点
Set集合
//实例化
Set set =new HashSet();
//加入元素
for(int i=0;i<s1.length();i++){
set.add(s1.charAt(i));
}
[Link][https://leetcode-cn.com/problems/check-permutation-lcci/ ]
Previous
[首页图片更新]2020.08.04
Newer