C 语言

关注公众号 jb51net

关闭
首页 > 软件编程 > C 语言 > Java C++ 判定是否为字符重排

Java C++题解leetcode判定是否为字符重排

作者:AnjaVon

这篇文章主要为大家介绍了Java C++题解leetcode判定是否为字符重排,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

题目要求

思路一:排序

Java

class Solution {
    public boolean CheckPermutation(String s1, String s2) {
        if(s1.length() != s2.length())
            return false;
        char[] sort1 = s1.toCharArray();
        Arrays.sort(sort1);
        char[] sort2 = s2.toCharArray();
        Arrays.sort(sort2);
        return Arrays.equals(sort1, sort2);
    }
}

C++

class Solution {
public:
    bool CheckPermutation(string s1, string s2) {
        if (s1.size() != s2.size())
            return false;
        sort(s1.begin(), s1.end());
        sort(s2.begin(), s2.end());
        return s1 == s2;
    }
};

Rust

impl Solution {
    pub fn check_permutation(s1: String, s2: String) -> bool {
        if s1.len() != s2.len() {
            false
        }
        else {
            let (mut sort1, mut sort2) = (s1.as_bytes().to_vec(), s2.as_bytes().to_vec());
            sort1.sort();
            sort2.sort();
            sort1 == sort2
        }
    }
}

思路二:词频统计

Java

class Solution {
    public boolean CheckPermutation(String s1, String s2) {
        if(s1.length() != s2.length())
            return false;
        int[] freq = new int[128];
        int diff = 0;
        for (int i = 0; i < s1.length(); i++) {
            if (++freq[s1.charAt(i)] == 1)
                diff++;
            if (--freq[s2.charAt(i)] == 0)
                diff--;
        }
        return diff == 0;
    }
}

C++

class Solution {
public:
    bool CheckPermutation(string s1, string s2) {
        if (s1.size() != s2.size())
            return false;
        int freq[128];
        memset(freq, 0, sizeof(freq));
        int diff = 0;
        for (int i = 0; i < s1.size(); i++) {
            if (++freq[s1[i]] == 1)
                diff++;
            if (--freq[s2[i]] == 0)
                diff--;
        }
        return diff == 0;
    }
};

Rust

impl Solution {
    pub fn check_permutation(s1: String, s2: String) -> bool {
        s1.len() == s2.len() && s1.bytes().zip(s2.bytes()).fold(vec![0; 128], |mut freq, (c1, c2)| {
            freq[c1 as usize] += 1;
            freq[c2 as usize] -= 1;
            freq
        }).into_iter().all(|diff| diff == 0)
    }
}

总结

简单模拟题、快乐结束~

有些语言不能改的字符串在这种时候真是烦烦……

以上就是Java C++题解leetcode判定是否为字符重排的详细内容,更多关于Java C++ 判定是否为字符重排的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文