[LeetCode] Valid Anagram 验证变位词

简介:

Given two strings s and t, write a function to determine if t is an anagram of s.

For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.

Note:
You may assume the string contains only lowercase alphabets.

这不算一道难题,核心点就在于使用哈希表映射,我们还是用一个数组来代替哈希表,使用类似方法的题目有Minimum Window Substring 最小窗口子串Isomorphic Strings 同构字符串Longest Substring Without Repeating Characters 最长无重复子串 和 1.1 Unique Characters of a String 字符串中不同的字符。我们先判断两个字符串长度是否相同,不相同直接返回false。然后把s中所有的字符出现个数统计起来,存入一个大小为26的数组中,因为题目中限定了输入字符串为小写字母组成。然后我们再来统计t字符串,如果发现不匹配则返回false。 参见代码如下:

class Solution {
public:
    bool isAnagram(string s, string t) {
        if (s.size() != t.size()) return false;
        int m[26] = {0};
        for (int i = 0; i < s.size(); ++i) ++m[s[i] - 'a'];
        for (int i = 0; i < t.size(); ++i) {
            if (--m[t[i] - 'a'] < 0) return false;
        }
        return true;
    }
};

本文转自博客园Grandyang的博客,原文链接:验证变位词[LeetCode] Valid Anagram ,如需转载请自行联系原博主。

相关文章
|
5月前
|
存储 canal 算法
[Java·算法·简单] LeetCode 125. 验证回文串 详细解读
[Java·算法·简单] LeetCode 125. 验证回文串 详细解读
49 0
|
2月前
|
Python
【Leetcode刷题Python】946. 验证栈序列
LeetCode题目“946. 验证栈序列”的Python解决方案,通过模拟栈的压入和弹出操作来验证给定的两个序列是否能通过合法的栈操作得到。
23 6
|
4月前
|
存储 SQL 算法
LeetCode 题目 65:有效数字(Valid Number)【python】
LeetCode 题目 65:有效数字(Valid Number)【python】
|
4月前
力扣经典150题第二十五题:验证回文串
力扣经典150题第二十五题:验证回文串
29 0
|
4月前
|
canal 算法 数据可视化
LeetCode 125题:验证回文串
LeetCode 125题:验证回文串
|
4月前
|
存储 算法 Java
【经典算法】LeetCode 125. 验证回文串(Java/C/Python3实现含注释说明,Easy)
【经典算法】LeetCode 125. 验证回文串(Java/C/Python3实现含注释说明,Easy)
21 0
|
5月前
|
C++ Python
leetcode-98:验证二叉搜索树
leetcode-98:验证二叉搜索树
53 1
|
5月前
|
Go
golang力扣leetcode 98. 验证二叉搜索树
golang力扣leetcode 98. 验证二叉搜索树
24 0
|
5月前
|
测试技术
leetcode98验证二叉搜索树刷题打卡
leetcode98验证二叉搜索树刷题打卡
28 0
|
5月前
leetcode-125:验证回文串
leetcode-125:验证回文串
45 0