LeetCode/solutions/242. Valid Anagram.md

46 lines
1.5 KiB
Markdown
Raw Normal View History

2018-09-14 11:09:51 +00:00
# [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;
}
};
```