Leetcode-383-Ransom Note

superorange 2022/07/14 362Views

Ransom Note

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

Description:

Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.

Each letter in magazine can only be used once in ransomNote.

Idea:

solution

Step1:create the array with the size is 26(all letters), use it to record all elements and corresponding number of their Occurrence

Step2: record the magzine firstly and record the number with increase, record the ransomNote secondly and record hte number with decrease.

Step3: becasue the elements of ransomNote should be included in the magazine, so if the number of same element’s<0, means there exists difference.

Code:

class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        //because 26 letters,so create array(26) to record the number of times that each letter appeared
        int[] result = new int[26];
        //record all element and coressponding times by increasing
        for(char x:magazine.toCharArray()){
            result[x-'a'] +=1;
        }
        //record all element of ransomNote and coressponding times by decreasing
        for(char x:ransomNote.toCharArray()){
            result[x-'a'] -=1;
        }
         //becasue the elements of ransomNote should be included in the  magazine, so if the number of same element's<0, means there exists difference
        for(int i:result){
            if(i<0){
                return false;
            }
        }
        return true;
    }
}