level - medium
[문제 내용]
주어진 문자열이 subsequence 인지 판별하여 subsequence의 수를 반환
[example 1]
Input: s = "abcde", words = ["a","bb","acd","ace"]
Output: 3
Explanation: There are three strings in words that are a subsequence of s: "a", "acd", "ace".
[example 2]
Input: s = "dsahjpjauf", words = ["ahjpjau","ja","ahbwzgqnuk","tnmlanowax"]
Output: 2
[해결 방법]
간단하게 word를 구성하는 각 문자의 존재여부를 이용해 판단하였다.
class Solution {
public int numMatchingSubseq(String s, String[] words) {
int result = 0;
for(String word : words) {
StringBuilder sb = new StringBuilder(s);
boolean isSub = true; // subsequence인지 판별
for(int i=0; i<word.length(); i++) {
String ch = String.valueOf(word.charAt(i));
int idx = sb.indexOf(ch);
if(idx == -1) {
isSub = false;
break;
}
sb.delete(0, idx+1);
}
if(isSub) {
result++;
}
}
return result;
}
}