【leetcode】【easy】242. Valid Anagram

mac2024-05-17  30

242. Valid Anagram

Given two strings s and t , write a function to determine if t is an anagram of s.

Example 1:

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

Example 2:

Input: s = "rat", t = "car" Output: false

Note: You may assume the string contains only lowercase alphabets.

Follow up: What if the inputs contain unicode characters? How would you adapt your solution to such case?

题目链接:https://leetcode.com/problems/valid-anagram/

法一:数组

class Solution { public: bool isAnagram(string s, string t) { if(s.length()!=t.length()) return false; int record[26]={0}; for(int i=0; i<s.length();++i){ record[s[i]-'a']++; } for (int i=0; i<t.length();++i){ record[t[i]-'a']--; if(record[t[i]-'a']<0) return false; } return true; } };

法二:map

class Solution { public: bool isAnagram(string s, string t) { if(s.length()!=t.length()) return false; unordered_map<char,int> record; for(int i=0; i<s.length();++i){ record[s[i]]++; } for (int i=0; i<t.length();++i){ record[t[i]]--; if(record[t[i]]<0) return false; } return true; } };
最新回复(0)