Java implementation LeetCode 383 ransom letter

383. ransom letter

Given a ransom channel (ransom) and a string magazine (magazine) string, the first string is determined ransom can consists of a second character string inside the magazines. If you can constitute, return true; otherwise false.

(Title Description: In order not to expose ransom letter writing, from the search needs of each magazine letters to form words to express the meaning.)

note:

You can assume two strings contain only lowercase letters.

canConstruct(“a”, “b”) -> false
canConstruct(“aa”, “ab”) -> false
canConstruct(“aa”, “aab”) -> true

PS:

String.indexof (a, b)
from b index began to look for a character

class Solution {
   public boolean canConstruct(String ransomNote, String magazine) {
        if (ransomNote.length() > magazine.length()) {
            return false;
        }
        int[] chars = new int[26];
        for (int i = 0; i < ransomNote.length(); i++) {
            char c = ransomNote.charAt(i);
            int index = magazine.indexOf(c, chars[c - 'a']);
            if (index == -1) {
                return false;
            }
            chars[c - 'a'] = index + 1;
        }
        return true;
    }
}
Released 1496 original articles · won praise 20000 + · views 1.89 million +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/104807623