[LeetCode-Easy]383. Ransom Note-勒索信问题

题目:

Given an arbitrary ransom note string and another string containing letters from all the magazines,
write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false
Note:
You may assume that both strings contain only lowercase letters.
 canConstruct("a", "b") -> false
 canConstruct("aa", "ab") -> false
 canConstruct("aa", "aab") -> true

思路:

先给大家解题意,这题真拐了好大圈,又是勒索信又是杂志的,其实就是一个字符出现频数的问题。笔者最开始方向搞错,当成了包含字符问题,结果各种错。上网找了这题大意才勉强了解题意,只能说这题不难,但是想看明白题意确实挺难TOT~~~我在代码中加入了注释,这样会更好理解一些。

这里如果想自己用编译器测试的话,建议不要使用他给的案例,偶然性很大,笔者给出一个案例,大家可以自己尝试使用。如果返回值对了,证明应该是正确的结果:

canConstruct(""fffbfg"", ""effjfggbffjdgbjjhhdegh"")
  期望结果为true

代码:

   public boolean canConstruct(String ransomNote, String magazine) {
    Map charmap = new HashMap<>();
    //循环把杂志中出现的单个字符计数,确定每个字符的出现频数~~
    for(int i = 0; i

你可能感兴趣的:([LeetCode-Easy]383. Ransom Note-勒索信问题)