LeetCode之Ransom Note (Java+C)
来源:互联网 发布:proxifier linux版 编辑:程序博客网 时间:2024/06/06 00:04
题意:
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") -> falsecanConstruct("aa", "ab") -> falsecanConstruct("aa", "aab") -> true
题意确实很绕,表示没看明白,后来上网翻译了下才理解了,可以很简单的理解为:前面的字符串ransomNote能否完全由后面的字符串magazine的字符所组成(都只考虑为小写字母情况)
Java代码:
public class Solution { public boolean canConstruct(String ransomNote, String magazine) { char[] ransoms = ransomNote.toCharArray(); char[] magazines = magazine.toCharArray(); for(int i = 0; i < ransoms.length; i++) { for(int j = 0; j < magazines.length; j++) { if(ransoms[i] == magazines[j]) { ransoms[i] = 0; magazines[j] = 0; break; } } } for(char r : ransoms) { if(r != 0) return false; } return true; }}
C代码:
bool canConstruct(char* ransomNote, char* magazine) { int ransomLen = sizeof(ransomNote); int magazineLen = sizeof(magazine); for(int i = 0; i < ransomLen; i++) { for(int j = 0; j < magazineLen; j++) { if(ransomNote[i] == magazine[j]) { ransomNote[i] = 0; magazine[j] = 0; break; } } } for(int i = 0; i < ransomLen; i++) { if(ransomNote[i] != 0) return false; } return true;}
解题思路:遍历数组,一一比对,相同的话,相应两数组的元素均置零!最后重新遍历ransomNote数组,如果存在非零元素,说明不符合要求,返回false,反之返回true
0 0
- LeetCode之Ransom Note (Java+C)
- [LeetCode] Ransom Note (java)
- 【LeetCode-383】Ransom Note(C++)
- leetcode-383. Ransom Note java
- [LeetCode-383]Ransom Note(java)
- LeetCode-383. Ransom Note (Java)
- LeetCode 383. Ransom Note 题解(C++)
- LeetCode 383:Ransom Note (c++)
- LeetCode之路:383. Ransom Note
- 【LeetCode】383 Ransom Note(java)
- leetcode-383. Ransom Note
- [leetcode] 383. Ransom Note
- LeetCode:383 Ransom Note
- 【Leetcode】Ransom Note
- LeetCode 383. Ransom Note
- Leetcode Ransom Note
- LeetCode#383 Ransom Note
- leetcode 383. Ransom Note
- 工厂方法模式(Factory Method Pattern)
- 中兴软件研发 综合面
- Machine Learning-1 :the definitions(maybe)
- JSP Expecting "jsp:param" standard action with "name" and "value" attributes
- Runable 周期任务
- LeetCode之Ransom Note (Java+C)
- Ajax基础
- C语言笔记
- (七)zookeeper 管理配置节点
- linux的启动流程分析-研读
- IntelliJ IDEA集成svn
- Spring 计划任务
- apache2.4实现tomcat负载均衡
- Memcached--基本使用命令