给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串 ransom 能不能由第二个字符串 magazines 里面的字符构成。如果可以构成,返回 true ;否则返回 false。
(题目说明:为了不暴露赎金信字迹,要从杂志上搜索各个需要的字母,组成单词来表达意思。杂志字符串中的每个字符只能在赎金信字符串中使用一次。)
注意:
你可以假设两个字符串均只含有小写字母。
canConstruct(“a”, “b”) -> false canConstruct(“aa”, “ab”) -> false canConstruct(“aa”, “aab”) -> true
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ransom-note
思路:
简单描述题目就是后一个字符串中是否包含所有的前一个字符串中的字符,如果全部包含就返回true否则false 先见字符串转换成字符数组,遍历两个数组,进行比较即可
class Solution {public boolean canConstruct(String ransomNote, String magazine) {char [] arr1 = ransomNote.toCharArray();char [] arr2 = magazine.toCharArray();int start1 = 0;int start2 = 0;while (start1 < arr1.length){while (start2 < arr2.length){// 如果是充值的‘-’就直接跳过if (arr2[start2] == '-'){start2++;}else if (start1 < arr1.length && arr1[start1] == arr2[start2]){// 如果两个相等就不能再用了第一个数组直接加一后一个数组需要重置到第一个但是不能重复用所以// 把用过的arr2中的值置为‘-’arr2[start2] = '-';start1++;start2 = 0;}else {start2++;}}// 后一个数组比较完了就退出break;}return start1 == arr1.length;}}
