zoukankan      html  css  js  c++  java
  • Leetcode 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. 



    Each 
letter
 in
 the
 magazine 
string 
can
 only 
be
 used 
once
 in
 your 
ransom
 note.

    Note:
    You may assume that both strings contain only lowercase letters.

    canConstruct("a", "b") -> false
    canConstruct("aa", "ab") -> false
    canConstruct("aa", "aab") -> true

    题目大意:给两个string,判断第一个string能否由第二个string里面所含有的字母组成,
    第二个string里面的所有字母只能使用一次

    分析:建立一个hash数组,对第二个string遍历并记录每个字符出现的次数,然后遍历第一个string,
    如果有出现hash里面不存在的字符,那么return false

     1 class Solution {
     2 public:
     3     bool canConstruct(string ransomNote, string magazine) {
     4         int a[26] = {0}, lenr = ransomNote.length(), lenm = magazine.length(), i;
     5         for(i = 0; i < lenm; i++)
     6             a[magazine[i] - 'a']++;
     7         for(i = 0; i < lenr; i++)
     8             if(a[ransomNote[i] - 'a'] == 0)
     9                 return false;
    10             else
    11                 a[ransomNote[i] - 'a']--;
    12         return true;
    13     }
    14 };
     
  • 相关阅读:
    笨办法学习python之hashmap
    python实现三级菜单源代码
    ql的python学习之路-day3
    ql的python学习之路-day2
    Spring的数据库开发
    Spring学习之Aspectj开发实现AOP
    spring学习之依赖注入DI与控制反转IOC
    spring学习之第一个spring程序
    spring学习之spring入门
    Java线程(一)——创建线程的两种方法
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/5827837.html
Copyright © 2011-2022 走看看