|
| 1 | +package com.leetcode.strings; |
| 2 | + |
| 3 | +/** |
| 4 | + * Problem: https://leetcode.com/problems/ransom-note/ |
| 5 | + * |
| 6 | + * @author rampatra |
| 7 | + * @since 2019年04月19日 |
| 8 | + */ |
| 9 | +public class RansomNote { |
| 10 | + |
| 11 | + /** |
| 12 | + * Runtime: <a href="https://leetcode.com/submissions/detail/223597898/">4 ms/a>. |
| 13 | + * |
| 14 | + * @param ransomNote |
| 15 | + * @param magazine |
| 16 | + * @return |
| 17 | + */ |
| 18 | + public static boolean canConstruct(String ransomNote, String magazine) { |
| 19 | + char[] charCount = new char[26]; |
| 20 | + |
| 21 | + for (int i = 0; i < magazine.length(); i++) { |
| 22 | + charCount[magazine.charAt(i) - 'a']++; |
| 23 | + } |
| 24 | + |
| 25 | + for (int i = 0; i < ransomNote.length(); i++) { |
| 26 | + if (charCount[ransomNote.charAt(i) - 'a']-- == 0) { |
| 27 | + return false; |
| 28 | + } |
| 29 | + } |
| 30 | + return true; |
| 31 | + } |
| 32 | + |
| 33 | + public static void main(String[] args) { |
| 34 | + System.out.println(canConstruct("", "")); |
| 35 | + System.out.println(canConstruct("a", "a")); |
| 36 | + System.out.println(canConstruct("ab", "ab")); |
| 37 | + System.out.println(canConstruct("aab", "ab")); |
| 38 | + } |
| 39 | +} |
0 commit comments