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;
    }
};

发布了28 篇原创文章 · 获赞 1 · 访问量 375

猜你喜欢

转载自blog.csdn.net/Zahb44856/article/details/104083493