December 9, 2023

Viiisit [LeetCode] - 242. Valid Anagram

#php#javascript#ruby

keep learning, keep coding!

Problem - Valid Anagram

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

翻譯蒟蒻

檢查兩個字串是否為重組字的問題。給定 s 與 t 兩個字串,t 要是透過 s 去重組而成的字串。


Solution - JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var isAnagram = function(s, t) {
if (s.length !== t.length) return false;
let map = {};
for (let i = 0; i < s.length; i++) {
map[s[i]] = map[s[i]] ? map[s[i]] + 1 : 1;
}
for (let i = 0; i < t.length; i++) {
if (!map[t[i]]) return false;
map[t[i]]--;
}
};

Solution - Ruby

Solution 1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def is_anagram(s, t)
return false if s.length != t.length

# 用來存儲字串 s, t 中每個字母的出現次數,default 為 0。
s_hash = Hash.new(0)
t_hash = Hash.new(0)

s.each_char do |char|
s_hash[char] += 1
end
t.each_char do |char|
t_hash[char] += 1
end
s_hash == t_hash
end

Solution 2:

1
2
3
4
def is_anagram(s, t)
# chars 可以將字串轉為個別字母的陣列
s.chars.sort == t.chars.sort
end

Solution - PHP

Solution 1:

1
2
3
4
5
6
7
function isAnagram($s, $t) {
$s = str_split($s);
$t = str_split($t);
sort($s);
sort($t);
return $s == $t;
}

Solution 2:

1
2
3
function isAnagram($s, $t) {
return count_chars($s, 1) == count_chars($t, 1);
}

PHP 方法筆記

LeetCode 傳送門 - Valid Anagram