28. Implement strStr()
Implement the strStr() function.
Given a haystack string and a needle string, find the first position of the needle string in the haystack string (starting from 0). If it does not exist, it returns -1.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
Problem-solving ideas
一直以来,做题有一个想法,自己认为可以做出来的方法一定会非常执着的去解。该方法采用BF的暴力匹配... 自己的方法较为复杂,需要考虑的地方也比较多,算是非常笨的方法了...
Code
class Solution {
public static int strStr(String haystack, String needle) {
//将几个特殊情况特殊处理
if("".equals(haystack) && "".equals(needle)){
return 0;
}
if("".equals(needle)){
return 0;
}
if(haystack.length() < needle.length()){
return -1;
}
//字符串转成字符数组
char[] charhays = haystack.toCharArray();
char[] charneedle = needle.toCharArray();
//比较每一位字符都相等时为true
boolean flag =false;
//charhays[i] == charneedle[0]记录位置
int index = -1;
//记录字串是否遍历完
int tag = 0;
for (int i = 0; i < charhays.length; i++) {
if(charhays[i] == charneedle[0]){
int k = i;
index = i;
for (int j = 0; j < charneedle.length; j++) {
if(k <charhays.length && charhays[k] == charneedle[j]){
flag = true;
tag ++;
}
k++;
}
//判断是否找到子串
if(tag == charneedle.length){
return index;
}
//必须置为0,才能进行下次匹配
tag = 0;
}
}
return -1;
}
}
test