383. Ransom Note

    xiaoxiao2021-03-25  162

    Given an arbitrary ransom notestring and another string containing letters from all the magazines, write afunction that will return true if the ransom note can be constructed from themagazines ; otherwise, it will return false.

     Each letter in the magazinestring can only be used once in your ransom note.

    Note:

    You may assume that bothstrings contain only lowercase letters.

     canConstruct("a","b") -> false

    canConstruct("aa","ab") -> false

    canConstruct("aa","aab") -> true

        翻译:给定一个任意的note字符串和包含所有字母的magzines另一个字符串,编写一个函数,如果可以从magzines的每个字符串的字母中构建成note字符串,则该函数将返回true; 否则,它将返回falsemagzines字符串中的每个字母只能在note中使用一次。

        注意:

        您可以假设两个字符串只包含小写字母。

        canConstruct(“a”,“b”) - > false

        canConstruct(“aa”,“ab”) - > false

        canConstruct(“aa”,“aab”) - > true

        题目比较简单,之间将magzines的每个字符分离出来放入List集合中,再遍历集合就行了。话不多说,上代码:

    public class Solution {

        public boolean canConstruct(StringransomNote, String magazine) {

            List ls=new LinkedList();

               for(int i=0;i<magazine.length();i++){

                     ls.add(magazine.charAt(i));

               }

               boolean flag=true;

               for(int i=0;i<ransomNote.length();i++){

                     char c=ransomNote.charAt(i);

                     if(!ls.contains(c)){

                          flag=false;

                          break;

                     }else{

                          ls.remove(new Character(c));//注意它的类型,如果不是应用类型,char会自动转换成int,这样会删除指定位置的节点,出现异常

                     }

               }

               return flag;

        }

    }

    转载请注明原文地址: https://ju.6miu.com/read-6981.html

    最新回复(0)