242. Valid Anagram

LeetCode easy original: C# #array #csharp #easy #leetcode #string
Der Aufgabentext wird für die gewählte Sprache aus dem Russischen übersetzt. Code bleibt unverändert.

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

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

Beispiel

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

Output: true

C# Lösung

zugeordnet/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++ Lösung

Auto-Entwurf, vor dem Einreichen prüfen
#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 Lösung

zugeordnet/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 Lösung

zugeordnet/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 Lösung

zugeordnet/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 Lösung

zugeordnet/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️⃣

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

2️⃣

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

3️⃣

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

😎

Stellen zu dieser Aufgabe

aktive Stellen with overlapping task tags are angezeigt.

Alle Stellen
Es gibt noch keine aktiven Stellen.