编程语言
首页 > 编程语言> > 程序员面试金典 面试题 01.02.判定是否互为字符重排

程序员面试金典 面试题 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% 的用户

标签:面试题,abc,示例,int,金典,s1,Solution,01.02,s2
来源: https://blog.csdn.net/m0_46334316/article/details/117093723