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;
}
}