【LeetCode】面试题 01.02. 判定是否互为字符重排(JAVA)

原题地址:https://leetcode-cn.com/problems/check-permutation-lcci/

题目描述:
给定两个字符串 s1 和 s2,请编写一个程序,确定其中一个字符串的字符重新排列后,能否变成另一个字符串。

示例 1:
输入: s1 = “abc”, s2 = “bca”
输出: true

示例 2:
输入: s1 = “abc”, s2 = “bad”
输出: false

说明:
0 <= len(s1) <= 100
0 <= len(s2) <= 100

代码:

所有字符做异或运算,如果最后结果为0,则为重排。

class Solution {
    public boolean CheckPermutation(String s1, String s2) {
        int res = 0;
        int m = s1.length(), n = s2.length();
        if(m != n) return false;
        for(int i = 0; i < m; i ++)
        {
            res = res ^ s1.charAt(i);
            res = res ^ s2.charAt(i);
        }
        if(res == 0) return true;
        return false;
    }
}

用数组标记出现的字母数。

class Solution {
    public boolean CheckPermutation(String s1, String s2) {
        int[] vec1 = new int[26];
        int m = s1.length(), n = s2.length();
        if(m != n) return false;
        for(int i = 0; i < m; i ++) vec1[s1.charAt(i) - 'a'] ++;
        for(int i = 0; i < m; i ++) vec1[s2.charAt(i) - 'a'] --;
        for(int i = 0; i < 26; i ++)
        {
            if(vec1[i] != 0) return false;
        }
        return true;
    }
}
发布了110 篇原创文章 · 获赞 4 · 访问量 9343

猜你喜欢

转载自blog.csdn.net/rabbitsockx/article/details/104334941