面试题 01.02. 判定是否互为字符重排
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/check-permutation-lcci
给定两个字符串 s1 和 s2,请编写一个程序,确定其中一个字符串的字符重新排列后,能否变成另一个字符串。
点击查看代码
class Solution {
public boolean CheckPermutation(String s1, String s2) {
//定义存储字符串长度的变量
int l1 = s1.length();
int l2 = s2.length();
//字符串长度不同直接返回 false
if(l1 != l2){
return false;
}
//定义存储字符的数组
int[] nums1 = new int[128];
int[] nums2 = new int[128];
//遍历字符串将字符存储到数组中
for(int i = 0;i < l1;i++){
nums1[s1.charAt(i)]++;
nums2[s2.charAt(i)]++;
}
//遍历数组判断两个字符是否相同有一个不同返回 false
for(int i = 0;i < 128;i++){
if(nums1[i] != nums2[i]){
return false;
}
}
//全都相同返回 true
return true;
}
}
示例 1:
输入: s1 = "abc", s2 = "bca"
输出: true
示例 2:
输入: s1 = "abc", s2 = "bad"
输出: false
说明:
0 <= len(s1) <= 100
0 <= len(s2) <= 100