*************
C++
topic: 242. 有效的字母异位词 - 力扣(LeetCode)
*************
Have a quick eye on the topic.
![]() |
The first instinct is sort algorithm. Sort is a standard library in c++. The basic usage of sort is as folllow.
vector<int> nums = {5, 2, 9, 1, 5, 6};
// 对 vector 排序
sort(nums.begin(), nums.end());
输出:1, 2, 5, 5, 6, 9
// 使用自定义比较函数实现降序排序
sort(nums.begin(), nums.end(), greater<int>());
输出: 9, 6, 5, 5, 2, 1
and it really works.
class Solution {
public:
bool isAnagram(string s, string t) {
// 对两个字符串进行排序
sort(s.begin(), s.end());
sort(t.begin(), t.end());
// 比较排序后的字符串是否相等
return s == t;
}
};
![]() |
But it something llike a trick. Snbsequence is the key point of this type of topics. Count the numbers of each letters in two strings. If there are 13 'a' in string s while 38 'a' in string t, then return false.
So for people can understand is count[a] = 13, which means letter a appears 13 times. But computer donot think so. Memory is everything to the computer. Computer knows 0 and 1. So count [1] = 13 means the object in storage position 1 shows up 13 times.
- ‘a’ corresponds to index 0
- ‘b’ corresponds to index 1
- ...
- ‘z’ corresponds to index 25
so make a count array, 26 elements in the array is 0 at first.
int count(26) = {0};
which meas 26 elements in the count array is 0;
| position | 0 | 1 | 2 | 3 | ... | 25 |
| corespond letter | a | b | c | d | z | |
| value | 0 | 0 | 0 | 0 | 0 | 0 |
counts[s[i] - 'a']++; // 对s中的字符加1
Suppose the string s = "hello"
| 字符 | c - 'a' 的值 |
|---|---|
'h' | 7 |
'e' | 4 |
'l' | 11 |
'l' | 11 |
'o' | 14 |
Then the code can be writen.
class Solution {
public:
bool isAnagram(string s, string t) {
int counts[26] = {0}; // 初始化计数数组
int countt[26] = {0};
// 统计字符出现次数
for (char c : s) counts[c - 'a']++;
for (char c : t) countt[c - 'a']++;
// 比较
return equal(begin(counts), end(counts), begin(countt));
}
};
![]() |
The type of the variables are changed from int to vector. It wii make changes.
// 初始化一个有13个数字的向量,全部为0
vector<int> diyname(13, 0)
class Solution {
public:
bool isAnagram(string s, string t) {
// int变成 Vector
vector<int> counts(26, 0); // 初始化计数数组
vector<int> countt(26, 0);
// 统计字符出现次数
for (char c : s) counts[c - 'a']++;
for (char c : t) countt[c - 'a']++;
// 比较
return counts == countt;
}
};
![]() |
But both the two methods initialize two arrays. What if just one array have to initialize?
class Solution {
public:
bool isAnagram(string s, string t) {
int count[26] = {0}; // 初始化计数数组
// 统计字符出现次数
for (char c : s) count[c - 'a']++;
for (char c : t) count[c - 'a']--;
// 检查所有字符的计数是否为零
for (int i = 0; i < 26; i++)
{
if (count[i] != 0)
{
return false;
}
}
return true;
}
};
![]() |
Methods are flexible. Follow the rules in c++ of each gramma and the code works. At the very begining, I confused about the gramma. Now I donot. Stepping in the new land always come up with strangers. After some practice, the strangers become neighbours.






被折叠的 条评论
为什么被折叠?



