title: Exercise of the Day (44): Valid Alphabets
categories:[Swords offer]
tags:[Daily practice]
date: 2022/04/18
Exercise of the Day (44): Effective Alphabetical Words
Given two strings s and t, write a function to determine whether t is an anagram of s.
Note: If each character in s and t appears the same number of times, then s and t are called anagrams of each other.
Example 1:
Input: s = "anagram", t = "nagaram"
output: true
Example 2:
Input: s = "rat", t = "car"
output: false
hint:
1 <= s.length, t.length <= 5 * 104
s and t contain only lowercase letters
Source: LeetCode
Link: https://leetcode-cn.com/problems/valid-anagram
Method 1: Sort
Thought analysis
t is an anagram of s equivalent to "two strings sorted equal". Therefore, we can sort the strings s and t respectively, and judge whether the sorted strings are equal. Furthermore, if the lengths of s and t
Different, t is not necessarily an anagram of s.
bool isAnagram(string s, string t) {
if (s.length() != t.length()) {
return false;
}
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t;
}
Method 2: Hash table
Thought analysis
Since the string contains only 26 lowercase letters, we can maintain a frequency array table with a length of 26, first traverse the frequency of the characters in the record string s, and then traverse the characters
String t, minus the corresponding frequency in table, if table[i]<0, it means that tt contains an extra character that is not in s, just return false
bool isAnagram(string s, string t) {
if (s.length() != t.length()) {
return false;
}
vector<int> table(26, 0);
for (auto &ch : s) {
table[ch - 'a']++;
}
for (auto &ch : t) {
table[ch - 'a']--;
if (table[ch - 'a'] < 0) {
return false;
}
}
return true;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。