242. Valid Anagram
given две строки s и t, return true, если t является анаграммой s, и false в противном случае.
Анаграмма — это слово или фраза, сформированная путём перестановки букв другого слова или фразы, обычно используя все исходные буквы ровно один раз.
Ejemplo
Input: s = "anagram", t = "nagaram"
Output: true
C# solución
coincidente/originalpublic bool IsAnagram(string s, string t) {
if (s.Length != t.Length) {
return false;
}
int[] table = new int[26];
for (int i = 0; i < s.Length; i++) {
table[s[i] - 'a']++;
table[t[i] - 'a']--;
}
foreach (int count in table) {
if (count != 0) return false;
}
return true;
}
C++ solución
borrador automático, revisar antes de enviar#include <bits/stdc++.h>
using namespace std;
// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
public bool IsAnagram(string s, string t) {
if (s.size() != t.size()) {
return false;
}
vector<int>& table = new int[26];
for (int i = 0; i < s.size(); i++) {
table[s[i] - 'a']++;
table[t[i] - 'a']--;
}
foreach (int count in table) {
if (count != 0) return false;
}
return true;
}
Java solución
coincidente/originalpublic boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
int[] table = new int[26];
for (int i = 0; i < s.length(); i++) {
table[s.charAt(i) - 'a']++;
table[t.charAt(i) - 'a']--;
}
for (int count : table) {
if (count != 0) {
return false;
}
}
return true;
}
JavaScript solución
coincidente/originalfunction isAnagram(s, t) {
if (s.length !== t.length) {
return false;
}
const count = Array(26).fill(0);
for (let i = 0; i < s.length; i++) {
count[s.charCodeAt(i) - 'a'.charCodeAt(0)]++;
count[t.charCodeAt(i) - 'a'.charCodeAt(0)]--;
}
for (let i = 0; i < 26; i++) {
if (count[i] !== 0) {
return false;
}
}
return true;
}
Python solución
coincidente/originaldef isAnagram(s, t):
if len(s) != len(t):
return False
count = [0] * 26
for char in s:
count[ord(char) - ord('a')] += 1
for char in t:
count[ord(char) - ord('a')] -= 1
if count[ord(char) - ord('a')] < 0:
return False
return True
Go solución
coincidente/originalfunc isAnagram(s string, t string) bool {
if len(s) != len(t) {
return false
}
count := [26]int{}
for i := range s {
count[s[i]-'a']++
count[t[i]-'a']--
}
for _, c := range count {
if c != 0 {
return false
}
}
return true
}
Algorithm
1️⃣
Создайте arreglo размером 26 для подсчета частот каждой буквы (поскольку s и t содержат только буквы от 'a' до 'z').
2️⃣
Пройдитесь по строке s, увеличивая счетчик соответствующей буквы. Затем пройдитесь по строке t, уменьшая счетчик для каждой буквы.
3️⃣
Проверьте, не опустился ли счетчик ниже нуля во время обхода строки t. Если это произошло, значит в t есть лишняя буква, которой нет в s, и следует вернуть false. Если после проверки всех букв все счетчики равны нулю, возвращайте true, указывая на то, что t является анаграммой s.
😎
Vacantes para esta tarea
Se muestran vacantes activas con etiquetas coincidentes.