mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
46 lines
1.5 KiB
Markdown
46 lines
1.5 KiB
Markdown
![]() |
# [242. Valid Anagram](https://leetcode.com/problems/valid-anagram/description/)
|
|||
|
# 思路
|
|||
|
题意就是:若s和t由同样的元素组成只是排列顺序不一样则返回true,否则返回false。
|
|||
|
## 思路一
|
|||
|
用两个长度为26的数组count1和count2分别记录s和t中字母a-z的出现的次数,最后比较两个数组的对应元素值是否相等,若全部相等则返回true,否则返回false;
|
|||
|
## 思路二*
|
|||
|
思路一的改进,令数组count = count1 - count2,则最后count中所有的元素全为0时返回true否则返回false。
|
|||
|
由此可见,只用分配一个数组即可,对s中出现的字母进行次数累加,对t中的出现的字母进行次数累减。
|
|||
|
# C++
|
|||
|
## 思路一
|
|||
|
```
|
|||
|
class Solution {
|
|||
|
public:
|
|||
|
bool isAnagram(string s, string t) {
|
|||
|
if(s.size() != t.size()) return false;
|
|||
|
|
|||
|
vector<int>count1(26), count2(26);
|
|||
|
for(int i = 0; i < s.size(); i++){
|
|||
|
count1[s[i] - 'a']++;
|
|||
|
count2[t[i] - 'a']++;
|
|||
|
}
|
|||
|
for(int i = 0; i < 26; i++)
|
|||
|
if(count1[i] != count2[i]) return false;
|
|||
|
return true;
|
|||
|
}
|
|||
|
};
|
|||
|
```
|
|||
|
## 思路二
|
|||
|
```
|
|||
|
class Solution {
|
|||
|
public:
|
|||
|
bool isAnagram(string s, string t) {
|
|||
|
if(s.size() != t.size()) return false;
|
|||
|
|
|||
|
vector<int>count(26, 0);
|
|||
|
for(int i = 0; i < s.size(); i++){
|
|||
|
count[s[i] - 'a']++;
|
|||
|
count[t[i] - 'a']--;
|
|||
|
}
|
|||
|
for(int i = 0; i < 26; i++)
|
|||
|
if(count[i] != 0) return false;
|
|||
|
return true;
|
|||
|
}
|
|||
|
};
|
|||
|
```
|