《重启12》
LeetCode分享-两个字符串前缀匹配-regionMatches万金油方法
题目
给你一个字符串 sentence 作为句子并指定检索词为 searchWord ,其中句子由若干用 单个空格 分隔的单词组成。请你检查检索词 searchWord 是否为句子 sentence 中任意单词的前缀。
如果 searchWord 是某一个单词的前缀,则返回句子 sentence 中该单词所对应的下标(下标从 1 开始)。如果 searchWord 是多个单词的前缀,则返回匹配的第一个单词的下标(最小下标)。如果 searchWord 不是任何单词的前缀,则返回 -1 。
字符串 s 的 前缀 是 s 的任何前导连续子字符串。
来源:力扣(LeetCode)
示例 1:
输入:sentence = “i love eating burger”, searchWord = “burg”
输出:4
示例 2:
输入:sentence = “this problem is an easy problem”, searchWord = “pro”
输出:2
示例 3:
输入:sentence = “i am tired”, searchWord = “you”
输出:-1
关键代码
public int isPrefixOfWord(String sentence, String searchWord) {
String[] sb=sentence.split(" ");
for (int i=0;i<sb.length;i++){
if(!(sb[i].length()<searchWord.length())){
if(sb[i].regionMatches(0,searchWord,0,searchWord.length())){
return i+1;
}
}
}
return -1;
}
regionMatches方法
这是regionMatches的源码
public boolean regionMatches(int toffset, String other, int ooffset,
int len) {
char ta[] = value;
int to = toffset;
char pa[] = other.value;
int po = ooffset;
// Note: toffset, ooffset, or len might be near -1>>>1.
if ((ooffset < 0) || (toffset < 0)
|| (toffset > (long)value.length - len)
|| (ooffset > (long)other.value.length - len)) {
return false;
}
while (len-- > 0) {
if (ta[to++] != pa[po++]) {
return false;
}
}
return true;
}
参数意义
-
toffset – 此字符串中子区域的起始偏移量。
-
other – 字符串参数。
-
ooffset – 字符串参数中子区域的起始偏移量。
-
len – 要比较的字符数。
思路
由题意可知到,要匹配sentence的前缀,意思就是截取sentence从头开始到searchWord的长度的字符进行匹配,而这个方法不仅仅能完成这道题,而且面对从内部匹对和后缀匹对等字符串匹对问题这个方法都是没有问题的,是一个万金油的字符串匹对方法。