今天和大家聊的问题叫做 实现 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; } }
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力。
