您的位置:首页 > 编程语言 > Java开发

leetcode-383. Ransom Note

2016-08-11 15:21 369 查看

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

import java.util.HashMap;
public class Solution {
public boolean canConstruct(String ransomNote, String magazine) {

boolean flag = true;

HashMap<Character,Integer> m_t = new HashMap<Character,Integer>();

for(int i = 0 ; i < magazine.length(); i ++){
if( null != m_t.get(magazine.charAt(i)))
m_t.put(magazine.charAt(i),m_t.get(magazine.charAt(i)) + 1);
else
m_t.put(magazine.charAt(i),1);

}

for(int i = 0 ; i < ransomNote.length(); i ++){
if( null == m_t.get(ransomNote.charAt(i)) || 0 == m_t.get(ransomNote.charAt(i))){
flag = false;
break;
}else
m_t.put(ransomNote.charAt(i),m_t.get(ransomNote.charAt(i)) - 1 );

}

return flag;
}
}


总结:这个题目也是比较简单,但是花了我不少时间,由于使用白板写代码,有一个地方的括号打错了。逻辑一直觉得没问题,多次想打开IDE调试哪里出bug了,最终还是找出来了地方。时间复杂度为O(m) + O(n);m和n分别为两个字符串的长度。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 算法