383身代金の手紙
身代金チャネル(身代金)と文字列マガジン(マガジン)の文字列を与えられた、最初の文字列は、決定された身代金缶は、マガジン内の第2の文字列で構成されています。あなたが構成することができる場合は、trueを返し、そうでない場合はfalse。
(タイトル説明:ために意味を表現する言葉を形成するために、各雑誌の文字の検索ニーズから、身代金の文字の書き込みが露出しません。)
注意:
あなたは、2つの文字列が小文字のみが含まれていると仮定することができます。
canConstruct(「」、「B」) - >偽
canConstruct(「AA」、「AB」) - >偽
canConstruct(「AA」、「AAB」) - >真
PS:
String.indexof(a、b)は
Bインデックスからは、文字を探し始めました
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;
}
}