给定两个字符串 s1
和 s2
,请编写一个程序,确定其中一个字符串的字符重新排列后,能否变成另一个字符串。
示例 1:
输入: s1 = "abc", s2 = "bca" 输出: true
示例 2:
输入: s1 = "abc", s2 = "bad" 输出: false
说明:
0 <= len(s1) <= 100
0 <= len(s2) <= 100
方法一:哈希表
使用哈希表作为字符计数器。
时间复杂度
方法二:排序
按照字符编码重新排序字符串,再检查两者一致性。
class Solution:
def CheckPermutation(self, s1: str, s2: str) -> bool:
n1, n2 = len(s1), len(s2)
if n1 != n2:
return False
counter = Counter()
for i in range(n1):
counter[s1[i]] += 1
counter[s2[i]] -= 1
return all(v == 0 for v in counter.values())
class Solution {
public boolean CheckPermutation(String s1, String s2) {
int n1 = s1.length();
int n2 = s2.length();
if (n1 != n2) {
return false;
}
int[] counter = new int[128];
for (int i = 0; i < n1; ++i) {
++counter[s1.charAt(i)];
--counter[s2.charAt(i)];
}
for (int v : counter) {
if (v != 0) {
return false;
}
}
return true;
}
}
var CheckPermutation = function (s1, s2) {
let n1 = s1.length,
n2 = s2.length;
if (n1 != n2) return false;
let counter = {};
for (let i = 0; i < n1; i++) {
let cur1 = s1.charAt(i),
cur2 = s2.charAt(i);
counter[cur1] = (counter[cur1] || 0) + 1;
counter[cur2] = (counter[cur2] || 0) - 1;
}
return Object.values(counter).every(v => v == 0);
};
func CheckPermutation(s1 string, s2 string) bool {
freq := make(map[rune]int)
for _, r := range s1 {
freq[r]++
}
for _, r := range s2 {
if freq[r] == 0 {
return false
}
freq[r]--
}
for _, v := range freq {
if v != 0 {
return false
}
}
return true
}
class Solution {
public:
bool CheckPermutation(string s1, string s2) {
int n1 = s1.size();
int n2 = s2.size();
if (n1 != n2) return 0;
vector<int> counter(128);
for (int i = 0; i < n1; ++i) {
++counter[s1[i]];
--counter[s2[i]];
}
for (int v : counter)
if (v) return 0;
return 1;
}
};
function CheckPermutation(s1: string, s2: string): boolean {
const n = s1.length;
const m = s2.length;
if (n !== m) {
return false;
}
const map = new Map<string, number>();
for (let i = 0; i < n; i++) {
map.set(s1[i], (map.get(s1[i]) ?? 0) + 1);
map.set(s2[i], (map.get(s2[i]) ?? 0) - 1);
}
for (const v of map.values()) {
if (v !== 0) {
return false;
}
}
return true;
}
function CheckPermutation(s1: string, s2: string): boolean {
return [...s1].sort().join('') === [...s2].sort().join('');
}
use std::collections::HashMap;
impl Solution {
pub fn check_permutation(s1: String, s2: String) -> bool {
let n = s1.len();
let m = s2.len();
if n != m {
return false;
}
let s1 = s1.as_bytes();
let s2 = s2.as_bytes();
let mut map = HashMap::new();
for i in 0..n {
*map.entry(s1[i]).or_insert(0) += 1;
*map.entry(s2[i]).or_insert(0) -= 1;
}
map.values().all(|i| *i == 0)
}
}
impl Solution {
pub fn check_permutation(s1: String, s2: String) -> bool {
let mut s1: Vec<char> = s1.chars().collect();
let mut s2: Vec<char> = s2.chars().collect();
s1.sort();
s2.sort();
s1 == s2
}
}