题目描述
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第 一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = "hello", needle = "ll"
输出: 2
示例 2:
输入: haystack = "aaaaa", needle = "bba"
输出: -1
说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。
代码: 只是想到的 不是最好的解法 建议看看源码
package leetcode.easy.week01;
public class problem28 {
public int strStr(String haystack, String needle) {
if(needle.length()<1){
return 0;
}
if(haystack.equals(needle)){
return 0;
}
String[] split = haystack.split(needle);
if(split.length>1 || (split.length==1 && split[0].length()<haystack.length())){
return split[0].length();
}else if(split.length==1){
return -1;
}
return 0;
}
public static void main(String[] args) {
problem28 pro=new problem28();
int i = pro.strStr("aaaksisoppi", "pi");
System.out.println("结果是:"+i);
}
}

本文详细解析了如何实现strStr()函数,该函数用于在haystack字符串中查找needle字符串首次出现的位置。通过示例展示了当needle为空字符串时的特殊处理,符合C语言的strstr()及Java的indexOf()定义。
1894

被折叠的 条评论
为什么被折叠?



