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.
Each letter in the magazine string can only be used once in your ransom note.
Example 1:
Input: ransomNote = "aa", magazine = "aab"
Output: true
Approach
Java
public class RansomNote {public static void main(String[] args) {String ransomNote = "aa", magazine = "aab";System.out.println(canConstruct(ransomNote, magazine));}static boolean canConstruct(String ransomNote, String magazine) {int f1[] = new int[26];int f2[] = new int[26];int n = ransomNote.length();int m = magazine.length();if (n > m)return false;for (int i = 0; i < n; i++)f1[ransomNote.charAt(i) - 'a']++;for (int i = 0; i < m; i++)f2[magazine.charAt(i) - 'a']++;for (int i = 0; i < 26; i++) {if (f2[i] < f1[i])return false;}return true;}}
C++
#include <bits/stdc++.h>using namespace std;bool canConstruct(string ransomNote, string magazine){int f1[26] = {0};int f2[26] = {0};int n = ransomNote.size(), m = magazine.size();if (n > m)return false;for (int i = 0; i < n; i++)f1[ransomNote[i] - 'a']++;for (int i = 0; i < m; i++)f2[magazine[i] - 'a']++;for (int i = 0; i < 26; i++){if (f2[i] < f1[i])return false;}return true;}int main(){string ransomNote = "aa", magazine = "aab";if (canConstruct(ransomNote, magazine))cout << "true";elsecout << "false";return 0;}
No comments:
Post a Comment