LeetCode/solutions/242. Valid Anagram.md
2019-09-13 23:08:41 +08:00

46 lines
1.5 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [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++
## 思路一
``` 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;
}
};
```
## 思路二
``` C++
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;
}
};
```