您的位置:首页 > 其它

leetcode - 383. Ransom Note

2018-02-28 17:12 253 查看
Problem: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

解释:    求解第二个字符串中是否包含第一个字符串的所有字符,一对一。
Solve:用排序查找的方式寻找咯,对两个字符串转换为字符数组,再进行排序,然后遍历第一个数组进行查找,匹配时两个都跳到下个字符进行比较,不匹匹配就第二个数组跳到下个字符,因为需要的是第一个字符数组都能在第二个数组中找到相同的字符。如果第一个数组都能找到与之匹配的字符,就返回TRUE,不然就是不能完全匹配了O(n),AC-24ms)。
public boolean canConstruct(String ransomNote, String magazine) {
if(ransomNote.length()<1){//
return true;
}
if(magazine.length()<1){
return false;
}
char[] s1=ransomNote.toCharArray();
char[] s2=magazine.toCharArray();
Arrays.sort(s1);
Arrays.sort(s2);
for (int i = 0,j = 0; j <s2.length&&i<s1.length ; j++) {//对数组一遍历
if(s1[i]==s2[j]){//找到相同字符,
i++;//匹配数组一的下个字符
if(i==s1.length){//数组一全部匹配完成
return true;
}
}
}
return false;
}
后记:这题意把我看醉了,开始以为是字符串匹配问题,后来又以为是顺序查找字符问题。。。后面才发现是字符匹配问题。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: