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
- leetcode-383. Ransom Note
- [leetcode] 383. Ransom Note
- LeetCode 383. Ransom Note
- leetcode 383. Ransom Note
- leetcode 383. Ransom Note
- 383.[LeetCode]Ransom Note
- leetcode 383. Ransom Note
- leetcode 383. Ransom Note
- Leetcode 383. Ransom Note
- 【leetcode】383. Ransom Note
- Leetcode 383. Ransom Note
- LeetCode 383. Ransom Note
- [LeetCode]383. Ransom Note
- LeetCode 383. Ransom Note
- [LeetCode]--383. Ransom Note
- LeetCode 383. Ransom Note
- leetcode 383. Ransom Note
- 【LeetCode】 383. Ransom Note
- The Letter Carrier's Rounds UVA
- sql server 安装
- BufferReader 的readling 方法,读取不到文件中的第一行
- zookeeper与euraka的选择
- activemq系列-常见问题解析
- LeetCode-383. Ransom Note
- android启动页面制作
- XML——属性
- 抽象类
- JVM的Metaspace,JAVA8以前是Permanent Area
- 导出数据库数据到excel表中(使用POI技术)
- English words page two
- Java中hashCode的作用
- 简单轮播图