Given two strings ransomNote and magazine, return trueif ransomNotecan be constructed by using the letters from magazineand falseotherwise.
Each letter in magazine can only be used once in ransomNote.
Solution
First solution came out my mind is convert two strings to two dictionaries, English letter as Key and Count as Value.
After converted, we iterate the Dictionary of ransomNote string, and check if any letter was exist or not in the Dictionary of magazine string, if not or count is not enough than return false.
C# Solution
Solution1 – two Dictionaries
public class Solution {
public bool CanConstruct(string ransomNote, string magazine) {
Dictionary<char, int> dictR = new Dictionary<char, int>();
Dictionary<char, int> dictM = new Dictionary<char, int>();
int num;
foreach(char i in ransomNote)
{
if (!dictR.TryGetValue(i,out num))
{
dictR.Add(i, 1);
}
else
{
dictR[i] = dictR[i]+1;
}
}
foreach(char i in magazine)
{
if (!dictM.TryGetValue(i,out num))
{
dictM.Add(i, 1);
}
else
{
dictM[i] = dictM[i]+1;
}
}
foreach(var item in dictR)
{
if (!dictM.TryGetValue(item.Key,out num) || dictM[item.Key]<item.Value)
{
return false;
}
}
return true;
}
}
Solution2 – one Dictionary
In the second solution, we used one dictionary to store and check.
public class Solution {
public bool CanConstruct(string ransomNote, string magazine) {
Dictionary<char, int> dictM = new Dictionary<char, int>();
int num;
foreach(char i in magazine)
{
if (!dictM.TryGetValue(i,out num))
{
dictM.Add(i, 1);
}
else
{
dictM[i] = dictM[i]+1;
}
}
foreach(char i in ransomNote)
{
if (!dictM.TryGetValue(i,out num))
{
return false;
}
else
{
num = dictM[i]-1;
if(num < 0)
{
return false;
}
dictM[i] = num;
}
}
return true;
}
}
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
Map<Character, Integer> mapM = new HashMap<Character, Integer>();
for (char m: magazine.toCharArray()) {
if(mapM.containsKey(m))
{
mapM.put(m, mapM.get(m)+1);
}
else
{
mapM.put(m, 1);
}
}
int num;
for (char r: ransomNote.toCharArray()) {
if(mapM.containsKey(r))
{
num = mapM.get(r)-1;
if(num < 0)
{
return false;
}
mapM.put(r, num);
}
else
{
return false;
}
}
return true;
}
}
Python3 Solution
Solution1 – two Dictionaries
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
dictR = {}
dictM = {}
for r in ransomNote:
if(r in dictR):
dictR[r] = dictR[r]+1
else:
dictR[r] = 1
for m in magazine:
if(m in dictM):
dictM[m] = dictM[m]+1
else:
dictM[m] = 1
for k, v in dictR.items():
if(k not in dictM):
return False
if(dictM[k]<v):
return False
return True
Solution2 – one Dictionary
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
dictM = {}
for m in magazine:
if(m in dictM):
dictM[m] = dictM[m]+1
else:
dictM[m] = 1
for r in ransomNote:
if(r in dictM):
num = dictM[r]-1
if(num < 0):
return False
dictM[r] = num
else:
return False
return True
JavaScript Solution
Solution1
/**
* @param {string} ransomNote
* @param {string} magazine
* @return {boolean}
*/
var canConstruct = function(ransomNote, magazine) {
var dictM = {}
for (let i = 0; i < magazine.length; i++) {
var m = magazine[i];
if(!(m in dictM))
{
dictM[m] = 1;
}
else
{
dictM[m] = dictM[m]+1;
}
}
for (let i = 0; i < ransomNote.length; i++) {
var r = ransomNote[i];
if(!(r in dictM))
{
return false;
}
else
{
var num = dictM[r]-1;
if(num < 0)
{
return false;
}
dictM[r] = num;
}
}
return true;
};
Conclusion
🧡If my solution helps, that is my honor!
🧡You can support me by clicking some ad, Thanks a lot
✅If you got any problem about the explanation, please feel free to let me know
function returnDefault(item)
{
item.innerText = "Copy"
item.style.color = "white"
item.style.backgroundColor = "CornflowerBlue";
}
if(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent) == false) //20221128 手機用戶移除copy功能
{
jQuery('code').each(function () {
var btn = document.createElement("button");
btn.innerHTML = "Copy";
btn.onmousedown = "event.preventDefault();";
btn.setAttribute('class', 'btnC');
btn.onclick = function(){
var k = this.nextSibling;
var textArea = document.createElement("textarea");
textArea.style.position = 'fixed';
textArea.style.top = 0;
textArea.style.left = 0;
textArea.style.width = '2em';
textArea.style.height = '2em';// We don't need padding, reducing the size if it does flash render.
textArea.style.padding = 0;// Clean up any borders.
textArea.style.border = 'none';
textArea.style.outline = 'none';
textArea.style.boxShadow = 'none';// Avoid flash of the white box if rendered for any reason.
textArea.style.background = 'transparent';textArea.value = k.textContent;document.body.appendChild(textArea);
textArea.focus();
textArea.select();var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';if(successful)
{
this.focus();
this.style.backgroundColor = "green";
this.innerText = "✔Copied"
openPop();
setTimeout(( ()=>returnDefault(this)),1850)
}document.body.removeChild(textArea);
};var parent = this.parentNode;
parent.insertBefore(btn, this);
});
}
var uagb_data = {"ajax_url":"https:\/\/zyrastory.com\/wp-admin\/admin-ajax.php","uagb_masonry_ajax_nonce":"556c237ce0"};
var uagb_data = {"ajax_url":"https:\/\/zyrastory.com\/wp-admin\/admin-ajax.php","uagb_masonry_ajax_nonce":"556c237ce0","uagb_grid_ajax_nonce":"bb8859361e"};
( function() {
let elements = document.querySelectorAll( '.uagb-post-grid.uagb-block-75c8ca0c .uagb-post-pagination-wrap a' );
elements.forEach(function(element) {
element.addEventListener("click", function(event){
event.preventDefault();
const link = event.target.getAttribute('href').match( /\/page\/\d+\// )?.[0] || '';
const regex = /\d+/; // regular expression to match a number at the end of the string
const match = link.match( regex ) ? link.match( regex )[0] : 1; // match the regular expression with the link
const pageNumber = parseInt( match ); // extract the number and parse it to an integer
window.UAGBPostGrid._callAjax({"btnBorderStyle":"none","overallBorderColor":"","block_id":"75c8ca0c","categories":"62","displayPostExcerpt":false,"displayPostComment":false,"displayPostImage":false,"imgSize":"medium","linkBox":false,"orderBy":"rand","paddingTop":20,"paddingBottom":20,"paddingRight":20,"paddingLeft":20,"excludeCurrentPost":true,"postPagination":true,"pageLimit":0,"paginationMarkup":"empty","imageRatio":"2-3","imgEqualHeight":true,"btnBorderLink":true,"btnBorderRadiusLink":true,"overallBorderLink":true,"overallBorderRadiusLink":true,"inheritFromTheme":true,"postType":"post","postDisplaytext":"No post found!","taxonomyType":"category","postsToShow":6,"enableOffset":false,"postsOffset":0,"displayPostDate":true,"excerptLength":15,"displayPostAuthor":false,"displayPostTitle":true,"displayPostTaxonomy":false,"hideTaxonomyIcon":true,"taxStyle":"default","displayPostTaxonomyAboveTitle":"withMeta","imgPosition":"top","bgOverlayColor":"#000000","overlayOpacity":"50","displayPostLink":true,"newTab":false,"ctaText":"Read More","btnHPadding":"","btnVPadding":"","columns":3,"tcolumns":2,"mcolumns":1,"align":"left","width":"wide","order":"desc","rowGap":20,"rowGapTablet":20,"rowGapMobile":20,"columnGap":20,"bgType":"color","bgColor":"#f6f6f6","titleTag":"h4","titleFontSize":"","titleFontSizeType":"px","titleFontFamily":"","titleLineHeightType":"em","titleLoadGoogleFonts":false,"metaColor":"","highlightedTextColor":"#fff","highlightedTextBgColor":"#3182ce","metaFontSize":"","metaFontSizeType":"px","metaFontFamily":"","metaLineHeightType":"em","metaLoadGoogleFonts":false,"excerptColor":"","excerptFontSize":"","excerptFontSizeType":"px","excerptFontFamily":"","excerptLineHeightType":"em","excerptLoadGoogleFonts":false,"displayPostContentRadio":"excerpt","ctaBgType":"color","ctaBgHType":"color","ctaFontSize":"","ctaFontSizeType":"px","ctaFontFamily":"","ctaLineHeightType":"em","ctaLoadGoogleFonts":false,"contentPadding":20,"ctaBottomSpace":0,"ctaBottomSpaceTablet":0,"ctaBottomSpaceMobile":0,"imageBottomSpace":15,"titleBottomSpace":15,"metaBottomSpace":15,"excerptBottomSpace":25,"contentPaddingUnit":"px","rowGapUnit":"px","columnGapUnit":"px","excerptBottomSpaceUnit":"px","paginationSpacingUnit":"px","imageBottomSpaceUnit":"px","titleBottomSpaceUnit":"px","metaBottomSpaceUnit":"px","ctaBottomSpaceUnit":"px","paddingBtnUnit":"px","mobilePaddingBtnUnit":"px","tabletPaddingBtnUnit":"px","paddingUnit":"px","mobilePaddingUnit":"px","tabletPaddingUnit":"px","isPreview":false,"taxDivider":", ","titleLetterSpacing":"","titleLetterSpacingType":"px","metaLetterSpacing":"","metaLetterSpacingType":"px","ctaLetterSpacing":"","ctaLetterSpacingType":"px","excerptLetterSpacing":"","excerptLetterSpacingType":"px","boxShadowColor":"#00000070","boxShadowHOffset":0,"boxShadowVOffset":0,"boxShadowBlur":"","boxShadowSpread":"","boxShadowPosition":"outset","boxShadowColorHover":"","boxShadowHOffsetHover":0,"boxShadowVOffsetHover":0,"boxShadowBlurHover":"","boxShadowSpreadHover":"","boxShadowPositionHover":"outset","borderWidth":"","borderStyle":"none","borderColor":"","borderRadius":"","blockName":"post-grid","equalHeight":true,"paginationBgActiveColor":"#e4e4e4","paginationActiveColor":"#333333","paginationBgColor":"#e4e4e4","paginationColor":"#777777","paginationLayout":"filled","paginationBorderColor":"#888686","paginationBorderSize":1,"paginationSpacing":20,"paginationAlignment":"left","paginationPrevText":"\u00ab Previous","paginationNextText":"Next \u00bb","layoutConfig":[["uagb\/post-image"],["uagb\/post-taxonomy"],["uagb\/post-title"],["uagb\/post-meta"],["uagb\/post-excerpt"],["uagb\/post-button"]],"post_type":"grid","equalHeightInlineButtons":false}, pageNumber, '75c8ca0c');
});
});
} )();
ai_front = {"insertion_before":"BEFORE","insertion_after":"AFTER","insertion_prepend":"PREPEND CONTENT","insertion_append":"APPEND CONTENT","insertion_replace_content":"REPLACE CONTENT","insertion_replace_element":"REPLACE ELEMENT","visible":"VISIBLE","hidden":"HIDDEN","fallback":"FALLBACK","automatically_placed":"Automatically placed by AdSense Auto ads code","cancel":"Cancel","use":"Use","add":"Add","parent":"Parent","cancel_element_selection":"Cancel element selection","select_parent_element":"Select parent element","css_selector":"CSS selector","use_current_selector":"Use current selector","element":"ELEMENT","path":"PATH","selector":"SELECTOR"};