avatar

superorange0707

  • Homepage
  • Tag
  • Category
Home Leetcode-383-Ransom Note
文章

Leetcode-383-Ransom Note

Posted 2022-07-14
4~5 min read

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;
    }
}
Leetcode
Leetcode Hash
Share

Further Reading

Apr 23, 2025

283 - Move Zero

[283 - Move Zero] 🔗 LeetCode Link Problem Description Given an integer array nums, move all 0's to the end of it while maintaining the relative order

Apr 23, 2025

27 - Remove Element

[27 - Remove Element] 🔗 LeetCode Link Problem Description Given an integer array nums and an integer val, remove all occurrences of val in nums in-pl

Apr 23, 2025

26 - Remove Duplicates from Sorted Array

[26 - Remove Duplicates from Sorted Array] 🔗 LeetCode Link Problem Description Given an integer array nums sorted in non-decreasing order, remove the

OLDER

Leetcode-202-Happy Number

NEWER

Leetcode-15-3Sum

Recently Updated

  • Migrating Jenkins SCM Using GitLab from Bitbucket: SCM URL Bulk Replacement
  • 283 - Move Zero
  • 27 - Remove Element
  • 26 - Remove Duplicates from Sorted Array
  • Migrating from Bitbucket to GitLab? Here’s how to keep your teams moving without missing a beat!

Trending Tags

Course two pointer Binary Tree Hash SQL Leetcode Error Recording Gitlab Bitbucket Devops

Contents