leetcode [383] ransom letter / Ransom Note, hash policy space for time

Topics address

https://leetcode-cn.com/problems/ransom-note/

Thinking

This question is very clear meaning of the questions, the first is to use a string ransom judge can not be constituted by the second string magazines inside the character, but to note here 2:01.

  • The first point "in order not to expose ransom writing letters, each letter search from the magazine need to form words to express the meaning" herein described in magazines have the letters can not be reused.

  • The second point, "you can assume two strings contain only lowercase letters." Note Only lowercase letters , it is important

General solution

Then the first idea is actually enumerate the violence, two for loop, we continue to look for, as follows:

// 时间复杂度: O(n^2)
// 空间复杂度:O(1)
class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        for (int i = 0; i < magazine.length(); i++) {
            for (int j = 0; j < ransomNote.length(); j++) {
                if (magazine[i] == ransomNote[j]) {
                    ransomNote.erase(ransomNote.begin() + j);
                    break;
                }
            }
        }
        if (ransomNote.length() == 0) {
            return true;
        }
        return false;
    }
};

Here time complexity is relatively high, but there is also a string delete erase operation is also time-consuming, of course, this code can also be had this question

We think the optimal solution

Optimization Solution

Because the topics are only lowercase letters, then we can use the hash-time strategy space for the array 26 also records the number of times the letter appeared in the magazine with a length, then use ransomNote to verify whether or not the array contains the required ransomNote All letters.
code show as below:

// 时间复杂度: O(n)
// 空间复杂度:O(1)
class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        int record[26] = {0};
        for (int i = 0; i < magazine.length(); i++) {
            record[magazine[i]-'a'] ++;
        }
        for (int j = 0; j < ransomNote.length(); j++) {
            record[ransomNote[j]-'a']--;
            if(record[ransomNote[j]-'a'] < 0) {
                return false;
            }
        }
        return true;
    }
};
Published 230 original articles · won praise 248 · views 260 000 +

Guess you like

Origin blog.csdn.net/youngyangyang04/article/details/104875000