程序员面试金典 面试题 01.02.判定是否互为字符重排

面试题 01.02.判定是否互为字符重排

题目描述

给定两个字符串s1s2,请编写一个程序,确定其中一个字符串的字符重新排列后,能否变成另一个字符串。

示例1

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

示例2

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

限制
0 <= len(s1) <= 100
0 <= len(s2) <= 100

示例代码
C++ 排序对比

#include <bits/stdc++.h>
using namespace std;

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

int main()
{
  	Solution s;
  	string str1_1 = "abc";
  	string str1_2 = "bca";
  	cout << s.CheckPermutation(str1_1,str1_2) << endl;

  	string str2_1 = "abc";
  	string str2_2 = "bad";
  	cout << s.CheckPermutation(str2_1,str2_2) << endl;	
	
	return 0;	
}

C++ 提交结果
执行用时:0 ms, 在所有 C++ 提交中击败了100.00% 的用户
内存消耗:5.8 MB, 在所有 C++ 提交中击败了96.26% 的用户

示例代码
Java 字符统计

public class Question01_02 {
    public static void main(String[] args) {
        Solution s = new Solution();

        System.out.println(s.CheckPermutation("abc","bca"));
        System.out.println(s.CheckPermutation("abc","bcd"));
    }
}

class Solution {
    public boolean CheckPermutation(String s1, String s2) {
        if (s1.length() != s2.length() )
            return false;
        int[] count = new int[256];
        for(char ch : s1.toCharArray())
            count[(int)ch]++;
        for (char ch : s2.toCharArray())
            count[(int)ch]--;
        for (int i : count)
            if (i != 0)
                return false;
        return true;
    }
}

Java 提交结果
执行用时:0 ms, 在所有 Java 提交中击败了100.00% 的用户
内存消耗:36 MB, 在所有 Java 提交中击败了78.75% 的用户

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

W.Lionel.Esaka

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值