Leecode no.28 实现 strStr()

package com.example.demo.leecode;

/**
* 实现 strStr() 函数。
* @Date 2020/12/29
* @author Tang
* 给定一个 haystack 字符串和一个 needle 字符串,
* 在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回  -1。
*
*/
public class ImplementStrstr {

private char[] charArray;
private char[] needleArray;

public int execute(String haystack, String needle){
if(haystack == null || needle == null){
return -1;
}
if(haystack.equals(needle)){
return 0;
}
charArray = haystack.toCharArray();
needleArray = needle.toCharArray();
//各种判断,恶心
if(needleArray.length == 0){
return 0;
}
if(charArray.length == 0 || charArray.length < needleArray.length){
return -1;
}

for(int i = 0; i < charArray.length; i++){
if(charArray[i] == needleArray[0] && ifOccurrence(i)){
return i;
}
}
return -1;
}

//判断charArray从Index位置开始,是否完全包含needleArray
private boolean ifOccurrence(int index){
int j = 0;
while(j < needleArray.length && index < charArray.length){
if(needleArray[j] != charArray[index]){
return false;
}
j++;
index++;
}
return j == needleArray.length;
}

public static void main(String[] args) {
String charArray = "mississippi";
String needleArray = "issippi";
int execute = new ImplementStrstr().execute(charArray, needleArray);
System.out.println(execute);

//还有一种简单解法
int i = charArray.indexOf(needleArray);
//。。。。
}

}
原文地址:https://www.cnblogs.com/ttaall/p/14207426.html