LeetCode刷题实战28:实现 strStr()
算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 实现 strStr(),我们先来看题面:
https://leetcode-cn.com/problems/implement-strstr/
Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
题意
样例
示例 1:
输入: haystack = "hello", needle = "ll"
输出: 2
示例 2:
输入: haystack = "aaaaa", needle = "bba"
输出: -1
题解
class Solution {
public int strStr(String haystack, String needle) {
return haystack.indexOf(needle);
}
}
class Solution {
public int strStr(String haystack, String needle) {
if(needle.equals("")||haystack.equals(needle)){
return 0;
}
int index=-1;
if(haystack.contains(needle)){
String[] str=haystack.split(needle);
if(str.length>=1){
index=str[0].length();
}else {
index=0;
}
}else{
index=-1;
}
return index;
}
}
上期推文: