LeetCode-383. Ransom Note

来源:互联网 发布:数据挖掘研究生 编辑:程序博客网 时间:2024/04/29 05:03

问题描述
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

题目分析
本题要求对比两个字符串ransomNote和magazine,如果ransomNote中的字符均可从magazine中找到,并且对应的字符个数不小于magazine,则返回true,否则false。假设:

ransomNot= "fffbfg" magazine= "effjfggbffjdgbjjhhdegh"

ransomNot中的所有字符均可以从magazine找到,并且相应的字符个数均小于magazine中的个数,故返回true。
注意:字符串可认为只含有小写字母。

解题思路
本题需要满足两个条件:
(1)magazine需要包含ransomNot中所有的字符。
(2)magazine所包含的ransomNot字符相对应的数量不小于ransomNot。

首先从ransomNot中的首个字符开始,与magazine中的字符逐个比较,若找到第一相同的,则将magazine中的这个相同的字符替换为除小写字母外的其他字符(题目中所有字符均只有小写字母),然后将ransomNot中的下一个字符与magazine比较,找到相同的就替换,依次完成ransomNot中所有字符的比较查找,如果某个字符没有在magazine中找到,则结束比较,返回false。
需要注意的是,当ransomNot为空时,需返回true。若magazine为空,而ransomNot不为空,则返回false。

代码(C语言)

#include <stdio.h>#include <string.h>#include <stdlib.h>#include <stdbool.h>                          //bool类型bool canConstruct(char* ransomNote, char* magazine) {    int i=0,j=0;    bool flag=true;    int size1=strlen(ransomNote);    int size2=strlen(magazine);    if(size1==0)                               //ransomNot为空        return true;    if(size1!=0 && size2==0)                   //magazine为空        return false;    char result[size2];    printf("sizez1=%d",size1);    for (j=0;j<size2;j++)              {        result[j]=magazine[j];                 //strcpy(result,magazine)    }                                               //result = (char* )malloc(sizeof(char)*(size2+1));    for (i=0;i<size1;i++)    {        for (j=0;j<size2;j++)        {            if(ransomNote[i]==result[j])        //逐个比较                {                    result[j]='0';              //找到到相同就替换                    break;                  }        }        if(j==size2)                           //未找到相同字符,结束比较,返回false            flag=false;        if(flag==false)            break;    }     return flag;}int main(){    char* ransomNote="a" ;    char* magazine="";    bool flag;    flag=canConstruct( ransomNote,  magazine);    printf("flag=%d",flag);    return 0;}

参考文献

[1] https://leetcode.com/problems/ransom-note/#/description
[2] http://codecloud.net/16807.html

原创粉丝点击