p383

LeetCode 383 Ransom Note 题解

1.题目:

canConstruct(“a”, “b”) -> false
canConstruct(“aa”, “ab”) -> false
canConstruct(“aa”, “aab”) -> true

题意:

两个字符串,r,m。用m中的字母(一个字母只能用一次)能否构成r.

2.解题思路:

见代码

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 

public class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
boolean ans=true;
if (ransomNote.equals("")) return true;
if (magazine.equals("")) return false;
int[] m=new int[26+5];
for (int i=0;i<magazine.length();i++)
{
m[magazine.charAt(i)-'a']++;
}
for (int i=0;i<ransomNote.length();i++)
{
if (m[ransomNote.charAt(i)-'a']<1) return false;
m[ransomNote.charAt(i)-'a']--;
}
return ans;
}
}


4.一些总结: