典型的近似子串問(wèn)題!
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
給你左右兩個(gè)字符串,判斷左側(cè)子串是否可以由右側(cè)字符串中抽取部分字符得到(右側(cè)字符串每個(gè)字母僅可用一次),全都是小寫字母。
思路:建立數(shù)組存儲(chǔ)每個(gè)字母出現(xiàn)的次數(shù)
public boolean canConstruct(String ransomNote, String magazine) { int[] letter = new int[26]; for(int i=0;i<magazine.length();i++) letter[magazine.charAt(i)-'a']++; for(int i=0;i<ransomNote.length();i++) letter[ransomNote.charAt(i)-'a']--; for(int i=0;i<26;i++) if(letter[i]<0) return false; return true; }新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注