LeetCode //C - 242. Valid Anagram

242. 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.
 

Example 1:

Input: s = “anagram”, t = “nagaram”
Output: true

Example 2:

Input: s = “rat”, t = “car”
Output: false

Constraints:

  • 1 < = s . l e n g t h , t . l e n g t h < = 5 ∗ 1 0 4 1 <= s.length, t.length <= 5 * 10^4 1<=s.length,t.length<=5104
  • s and t consist of lowercase English letters.

Follow up:

What if the inputs contain Unicode characters? How would you adapt your solution to such a case?

From: LeetCode
Link: 242. Valid Anagram


Solution:

Ideas:

This function first checks if the lengths of s and t are different, returning false if they are. Then it iterates through both strings, incrementing and decrementing counts for each letter. Finally, it checks if any counts are non-zero, returning false if any are. If all counts are zero, the function returns true, indicating that the strings are anagrams.

Code:
bool isAnagram(char * s, char * t) {
    if (strlen(s) != strlen(t)) {
        return false; // If lengths are different, they can't be anagrams
    }

    int counts[26] = {0}; // Initialize counts of each letter to 0

    // Increment counts for letters in s
    for (int i = 0; s[i] != '\0'; i++) {
        counts[s[i] - 'a']++;
    }

    // Decrement counts for letters in t
    for (int i = 0; t[i] != '\0'; i++) {
        counts[t[i] - 'a']--;
    }

    // Check if any counts are non-zero
    for (int i = 0; i < 26; i++) {
        if (counts[i] != 0) {
            return false;
        }
    }

    return true;
}

你可能感兴趣的:(LeetCode,leetcode,c语言,算法)