大纲
- 题目
- 地址
- 内容
- 解题
- 代码地址
题目
地址
https://leetcode.com/problems/valid-anagram/
内容
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
Example 1:
Input:s = “anagram”, t = “nagaram”
Output:true
Example 2:
Input:s = “rat”, t = “car”
Output:false
Constraints:
- 1 <= s.length, t.length <= 5 * 104
- s and t consist of lowercase English letters.
Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
解题
这题就是要检验两个字符串中是否包含相同的字母和个数。我们可以遍历第一个字符串,统计每个字符出现的次数。然后遍历第二个字符串,逐个减少对应字符出现的次数。如果最终每个字符数都是0,则表示它们符合检测。
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.size() != t.size()) return false;
vector<int> count(26, 0);
for (char c : s) {
count[c - 'a']++;
}
for (char c : t) {
count[c - 'a']--;
}
for (int i : count) {
if (i != 0) return false;
}
return true;
}
};
代码地址
https://github.com/f304646673/leetcode/blob/main/242-Valid-Anagram/cplusplus/src/solution.hpp