算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个号后续每天带大家做一道算法题,题目就从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.
题意
实现 strStr() 函数。给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
样例
示例 1:
输入: haystack = "hello", needle = "ll"
输出: 2
示例 2:
输入: haystack = "aaaaa", needle = "bba"
输出: -1
题解
看到题目,你是不是立马想到了这道题和 Java的 indexOf() 定义相符符,那我们可以直接用一行代码就解决了,哈哈 。
class Solution {
public int strStr(String haystack, String needle) {
return haystack.indexOf(needle);
}
}
这道题最简单的解法,就是将窗口内的子串与 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;
}
}
好了,今天的文章就到这里。