char [] text = {'H','e','l','L','o','H','e','l','L','o'};
char[] pat = {'H','e','?','l','o'}; //'?' stands for every possible sign
我们可以忽略字母是大写还是小写。
现在,我需要输出它发生的频率。
Output: He?lo is in HelLoHelLo 2x
我知道您可以使用“包含”之类的字符串方法,但是如何考虑问号?
最佳答案
public int matchCount(char[] text, char[] pattern) {
int consecCharHits = 0, matchCount = 0;
for (int i = 0; i < text.length; i++) {
if (text[i] == pattern[consecCharHits] || '?' == pattern[consecCharHits]) { // if char matches
consecCharHits++;
if (consecCharHits == pattern.length) { // if the whole pattern matches
matchCount++;
i -= consecCharHits - 1; // return to the next position to be evaluated
consecCharHits = 0; // reset consecutive char hits
}
} else {
i -= consecCharHits;
consecCharHits = 0;
}
}
return matchCount;
}