Leetcode - String - 383. Ransom Note(水题)

    xiaoxiao2026-03-28  15

    1. Problem Description

    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

     

    给出两个字符串,判断第一个字符串能否由第二个字符串构成,每个字符只能使用一次,假设都是小写。

     

    2. My solution(24ms)

    class Solution { public: bool canConstruct(string ransomNote, string magazine) { int cnt[26]; for(int i=0;i<26;i++) cnt[i]=0; int lenr=ransomNote.length(),lenm=magazine.length(); for(int i=0;i<lenm;i++) { int tmp=magazine[i]-'a'; cnt[tmp]++; } for(int i=0;i<lenr;i++) { int tmp=ransomNote[i]-'a'; cnt[tmp]--; if(cnt[tmp]<0) return false; } return true; } };
    转载请注明原文地址: https://ju.6miu.com/read-1308268.html
    最新回复(0)