本文次要记录一下leetcode之断定是否互为字符重排

题目

给定两个字符串 s1 和 s2,请编写一个程序,确定其中一个字符串的字符重新排列后,是否变成另一个字符串。示例 1:输出: s1 = "abc", s2 = "bca"输入: true 示例 2:输出: s1 = "abc", s2 = "bad"输入: false阐明:    0 <= len(s1) <= 100    0 <= len(s2) <= 100 起源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/check-permutation-lcci著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。

题解

class Solution {    public boolean CheckPermutation(String s1, String s2) {        if(s1.length() != s2.length()) {            return false;        }        int len = 'z' + 1;        int[] idx1 = new int[len];        int[] idx2 = new int[len];        for(int i=0; i<s1.length(); i++){            idx1[s1.charAt(i)] = idx1[s1.charAt(i)] + 1;            idx2[s2.charAt(i)] = idx2[s2.charAt(i)] + 1;        }        for(int i=0; i<len; i++){            if (idx1[i] != idx2[i]) {                return false;            }        }        return true;    }}

小结

这里别离保护两个字符串的字符的个数,而后遍历下判断每个字符的个数是否相等。

doc

  • 断定是否互为字符重排