【LeetCode】#28实现strStr()(Implement strStr())
题目描述
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例
示例 1:
输入: haystack = “hello”, needle = “ll”
输出: 2
示例 2:
输入: haystack = “aaaaa”, needle = “bba”
输出: -1
Description
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example
Example 1:
Input: haystack = “hello”, needle = “ll”
Output: 2
Example 2:
Input: haystack = “aaaaa”, needle = “bba”
Output: -1
解法
解法1:
class Solution {
public int strStr(String haystack, String needle) {
if(needle.length()>haystack.length()){
return -1;
}
if(needle.equals(haystack)){
return 0;
}
if(needle.equals("")){
return 0;
}
String[] strH = haystack.split("");
String[] strN = needle.split("");
int k = -1;
for(int i=0; i<strH.length; i++){
if(strH[i].equals(strN[0])){
k = i;
if(strH.length-i<strN.length){
return -1;
}
if(strN.length==1){
return k;
}else{
for(int j=0; j<strN.length; j++){
if(!strN[j].equals(strH[k])){
break;
}
k++;
if(j==strN.length-1){
return i;
}
}
}
}
}
return -1;
}
}
解法2:
class Solution {
public int strStr(String haystack, String needle) {
int num=needle.length();
for(int i=0;i<haystack.length()-num+1;i++){
String re=haystack.substring(i,i+num);
if(re.equals(needle))return i;
}
return -1;
}
}