242. Valid Anagram

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

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

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

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

 

Approach 1# Sorting: 

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
    bool isAnagram(string s, string t) {
        if (s.length() != t.length()) return false;
        sort(s.begin(), s.end());
        sort(t.begin(), t.end());
        for (int i = 0; i < s.length(); ++i) {
            if (s[i] != t[i])
                return false;
        }
        return true;
    }
};
Runtime: 28 ms

 

Approach 2# Hash Table:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
    bool isAnagram(string s, string t) {
        if (s.length() != t.length()) return false;
        vector<int> temp(26, 0);
        for (int i = 0; i < s.length(); ++i) {
            temp[s[i]-'a']++;
            temp[t[i]-'a']--;
        }
        for (int i = 0; i < 26; ++i) {
            if (temp[i] != 0) return false;
        }
        return true;
    }
};

Runtime: 8 ms, faster than 83.11% of C++ online submissions for Valid Anagram.

 

posted @   Veritas_des_Liberty  阅读(167)  评论(0编辑  收藏  举报
编辑推荐:
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 现代计算机视觉入门之:什么是图片特征编码
· .NET 9 new features-C#13新的锁类型和语义
· Linux系统下SQL Server数据库镜像配置全流程详解
阅读排行:
· Sdcb Chats 技术博客:数据库 ID 选型的曲折之路 - 从 Guid 到自增 ID,再到
· Winform-耗时操作导致界面渲染滞后
· Phi小模型开发教程:C#使用本地模型Phi视觉模型分析图像,实现图片分类、搜索等功能
· 语音处理 开源项目 EchoSharp
· drools 规则引擎和 solon-flow 哪个好?solon-flow 简明教程
点击右上角即可分享
微信分享提示