383. Ransom Note
- Total Accepted: 42641
- Total Submissions: 92212
- Difficulty: Easy
- Contributors: Admin
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
Subscribe to see which companies asked this question.
public class Solution {
public boolean canConstruct(String ransomNote, String magazine) {boolean flag=false;
if(magazine.indexOf(ransomNote)!=-1){
System.out.println("包含");
flag=true;
}
else{
//存储
char[] number=ransomNote.toCharArray();
char[] number2=magazine.toCharArray();
int temp=0;
for(int i=0;i<number.length;i++){
for(int j=0;j<number2.length;j++)
{
if(number[i]==number2[j]){
number2[j]=0;
++temp;
break;
}
}
}
if(temp==number.length)
{
flag=true;
}
else{
flag=false;
}
}
return flag;
}
}