题目描述:
方法一(暴力匹配):
从长字符串中取第一个字符与短字符串第一个字符比较,相等比较各自的下一个字符,直到不相等,如果此时匹配相等长度比短字符串小,则第一次没有找到,进行第二次,从长字符串取第二个字符与短字符串第一个字符比较,以此类推,直至长字符串比较完,或者比较完前找到等于短字符串的子串。
代码(Java实现):
class Solution {
public int strStr(String haystack, String needle) {
if(needle == null || needle.length() == 0){//字符串为空,返回0
return 0;
}
char[] hs = haystack.toCharArray();
char[] nd = needle.toCharArray();
int h = 0;//haystack字符串中的索引
while(h < haystack.length() - needle.length() +1){//while要满足的大条件
while(h < haystack.length() - needle.length() +1 && hs[h] != nd[0]){//找到与needle字符串第一个字符相等的haystack的字符索引
h++;
}
int n = 0;
int count = 0;
while(n < needle.length() && h < haystack.length() && hs[h] == nd[n]){//比较字符,同时记录相等的字符个数count
h++;
n++;
count++;
}
if(count == needle.length()){//如果count等于needle的长度,说明找到了,返回与needle第一个字符相等的haystack中字符的索引
return h - count;
}
h = h - count +1;//小于的话,回到之前paystack部分匹配的字符串的第二个索引,继续进行比较
}
return -1;//没找到返回-1
}
}
结果:
代码(C语言):
int strStr(char * haystack, char * needle){
int hslen = strlen(haystack);
int ndlen = strlen(needle);
if(ndlen == 0){
return 0;
}
for(int i = 0;i < hslen;i++){
if(hslen - i < ndlen){
return -1;
}
int n = i,m = 0;
while(m < ndlen && n < hslen && haystack[n] == needle[m]){
if(m == ndlen -1){
return i;
}
m++;
n++;
}
}
return -1;
}
结果:
方法二(分割子串匹配):
从长字符第一个字符开始分割出长度为短字符串长度的子串与短字符串比较,不相等,则取长字符串第二个字符开始的长度为短字符串长度的子串,直至长字符串比较完,或者成功找到匹配的子串。
代码(Java实现):
class Solution {
public int strStr(String haystack, String needle) {
if(needle == null || needle.length() == 0){
return 0;
}
int hslen = haystack.length(),ndlen = needle.length();
for(int i = 0;i < hslen - ndlen + 1;i++){
if(haystack.substring(i,i+ndlen).equals(needle)){//灵活运用分割字符串的substring方法,来匹配needle字符串
return i;
}
}
return -1;
}
}
结果: