1988coder

383. Ransom Note

Jan 5th, 2019
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.85 KB | None | 0 0
  1. // LeetCode URL: https://leetcode.com/problems/ransom-note/
  2. /**
  3.  * Time Complexity: O(R + M)
  4.  *
  5.  * Space Complexity: O(26) ~= O(1)
  6.  *
  7.  * R = Length of ransomNote string. M = Length of magazine string.
  8.  */
  9. class Solution {
  10.     public boolean canConstruct(String ransomNote, String magazine) {
  11.         if (ransomNote == null || magazine == null || magazine.length() < ransomNote.length()) {
  12.             return false;
  13.         }
  14.         if (ransomNote.length() == 0) {
  15.             return true;
  16.         }
  17.  
  18.         int[] charCount = new int[26];
  19.         for (char c : magazine.toCharArray()) {
  20.             charCount[c - 'a']++;
  21.         }
  22.  
  23.         for (char c : ransomNote.toCharArray()) {
  24.             if (charCount[c - 'a'] == 0) {
  25.                 return false;
  26.             }
  27.             charCount[c - 'a']--;
  28.         }
  29.  
  30.         return true;
  31.     }
  32. }
Add Comment
Please, Sign In to add comment