当前位置:网站首页>Ransom Letter Questions and Answers

Ransom Letter Questions and Answers

2022-08-10 19:57:00 little question mark we are friends

Given the stem:

Give you two strings: ransomNote and magazine , judge whether ransomNote can be composed of the characters in magazine.

Returns true if yes; false otherwise.

Each character in the magazine can only be used once in ransomNote.

Title source:

LeetCode


1. Example

The code is as follows (example):

Input: ransomNote = "aa", magazine = "ab"output: falseInput: ransomNote = "aa", magazine = "aab"output: true

2. Answers and NotesRemember

The code is as follows (Java):

class Solution {public boolean canConstruct(String ransomNote, String magazine) {int rLen = ransomNote.length();int mLen = magazine.length();char[] rChr = ransomNote.toCharArray();char[] mChr = magazine.toCharArray();// If the length of the ransomNote is greater than the length of the magazine, the ransomNote cannot be composed of the characters in the magazine.if(rLen > mLen) {return false;}// Create a count array to store the number of times each letter appears.The index of the array is 0-25, and the index value can be obtained by the difference of any two of the values ​​97-122 of a-z in the ASCII table.int[] cInt = new int[26];// Loop through the two character arrays respectively. When the letter appears in the magazine, the value of the count array is increased by one, and when the letter appears in the ransomNote, the value of the count array is reduced by one.for(char c:mChr) {// c - 'a' means to get the difference between the ASCII code of the current character and the ASCII code of the character 'a', which is the index of the character in the count array.cInt[c - 'a']++;}for(char c:rChr) {cInt[c - 'a']--;//If cInt[c - 'a'] is less than zero, then ransomNote cannot be composed of characters in magazine.if(cInt[c - 'a'] < 0) {return false;}}return true;}}

3.ASCII table


Summary

That's all for today. This article introduces the solution to the ransom note problem. Here is a memo for reference.

原网站

版权声明
本文为[little question mark we are friends]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/222/202208101902513702.html