55. Compare Strings / 158. Valid Anagram

55. Compare Strings / 158. Valid Anagram

Tag:

Hash Table, Map

Description:

55. Compare Strings

Compare two strings A and B, determine whether A contains all of the characters in B.

The characters in string A and B are all Upper Case letters.

Example
For A = “ABCD”, B = “ACD”, return true.

For A = “ABCD”, B = “AABC”, return false.

Notice
The characters of B in A are not necessary continuous or ordered.

158. Valid Anagram

Write a method anagram(s,t) to decide if two strings are anagrams or not.

Example
Example 1:

Input: s = “ab”, t = “ab”
Output: true
Example 2:

Input: s = “abcd”, t = “dcba”
Output: true
Example 3:

Input: s = “ac”, t = “ab”
Output: false
Challenge
O(n) time, O(1) extra space

Clarification
What is Anagram?

Two strings are anagram if they can be the same after change the order of characters.

Main Idea:

Easy Hash Table Problem. All we need to do is record the appearance times of each character using unordered_map/map(key: the character, key: times of appearance).

Frankly speaking, this problem is test the basic knowledges of using hash table structure. For more details of hash table, which is unordered_map/ map in C++, welcome to check my OOP study note of STL.

Code of:

Note there, the implementations of two problems are exactly same.

class Solution {
public:
    /**
     * @param s: The first string
     * @param t: The second string
     * @return: true or false
     */
    bool anagram(string &s, string &t) {
        // write your code here
        unordered_map<char, int> hash;
        for(char now : s){
            hash[now]++;
        }
        
        for(char now : t){
            if(hash.find(now) == hash.end()){
                return false;
            }
            
            if(hash[now] <= 0){
                return false;
            }
            hash[now]--;
        }
        return true;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值