当前位置:网站首页>Force buckle 3_ 383. Ransom letter

Force buckle 3_ 383. Ransom letter

2022-07-04 22:11:00 Don't sleep in class

Here are two strings :ransomNote and magazine , Judge ransomNote Can it be done by magazine The characters inside make up .

If possible , return true ; Otherwise return to false .

magazine Each character in can only be in ransomNote Used once in .

Example 1:

 Input :ransomNote = "a", magazine = "b"
 Output :false

Example 2:

 Input :ransomNote = "aa", magazine = "ab"
 Output :false

Example 3:

 Input :ransomNote = "aa", magazine = "aab"
 Output :true

source : Power button (LeetCode)

Java solution

class Solution {
    
    public boolean canConstruct(String ransomNote, String magazine) {
    
        if (ransomNote.length() > magazine.length()) {
    
            return false;
        }
        int[] cnt = new int[26];// Use counting 
        for (char c : magazine.toCharArray()) {
    
        //ToCharArray( ) Usage of , Convert a character in a string object into an array of characters .
            cnt[c - 'a']++;
        }
        for (char c : ransomNote.toCharArray()) {
    
            cnt[c - 'a']--;
            if(cnt[c - 'a'] < 0) {
    
                return false;
            }
        }
        return true;
    }
}

Python solution 1

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        if len(ransomNote) > len(magazine):
            return False
        return not collections.Counter(ransomNote) - collections.Counter(magazine)
        # Here we use the counting function collections.Counter() It's not easy to understand 

Python solution 2

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        for i in range(len(ransomNote)):
            if ransomNote[i] in magazine:
                magazine = magazine.replace(ransomNote[i],'',1)
                # It's used here replace() function , One found, one deleted 
            else:
                return False
        return True
原网站

版权声明
本文为[Don't sleep in class]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207042138559041.html