242. Valid Anagram

LeetCode easy original: C# #array #csharp #easy #leetcode #string
Le texte du problème est traduit du russe pour la langue sélectionnée. Le code reste inchangé.

given две строки s и t, return true, если t является анаграммой s, и false в противном случае.

Анаграмма — это слово или фраза, сформированная путём перестановки букв другого слова или фразы, обычно используя все исходные буквы ровно один раз.

Exemple

Input: s = "anagram", t = "nagaram"

Output: true

C# solution

correspondant/original
public 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++ solution

brouillon automatique, à relire avant soumission
#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 solution

correspondant/original
public 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 solution

correspondant/original
function 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 solution

correspondant/original
def 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 solution

correspondant/original
func 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️⃣

Создайте tableau размером 26 для подсчета частот каждой буквы (поскольку s и t содержат только буквы от 'a' до 'z').

2️⃣

Пройдитесь по строке s, увеличивая счетчик соответствующей буквы. Затем пройдитесь по строке t, уменьшая счетчик для каждой буквы.

3️⃣

Проверьте, не опустился ли счетчик ниже нуля во время обхода строки t. Если это произошло, значит в t есть лишняя буква, которой нет в s, и следует вернуть false. Если после проверки всех букв все счетчики равны нулю, возвращайте true, указывая на то, что t является анаграммой s.

😎

Vacancies for this task

offres actives with overlapping task tags are affichés.

Toutes les offres
Il n'y a pas encore d'offres actives.