Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // LeetCode URL: https://leetcode.com/problems/ransom-note/
- /**
- * Time Complexity: O(R + M)
- *
- * Space Complexity: O(26) ~= O(1)
- *
- * R = Length of ransomNote string. M = Length of magazine string.
- */
- class Solution {
- public boolean canConstruct(String ransomNote, String magazine) {
- if (ransomNote == null || magazine == null || magazine.length() < ransomNote.length()) {
- return false;
- }
- if (ransomNote.length() == 0) {
- return true;
- }
- int[] charCount = new int[26];
- for (char c : magazine.toCharArray()) {
- charCount[c - 'a']++;
- }
- for (char c : ransomNote.toCharArray()) {
- if (charCount[c - 'a'] == 0) {
- return false;
- }
- charCount[c - 'a']--;
- }
- return true;
- }
- }
Add Comment
Please, Sign In to add comment