力扣-28. 找出字符串中第一个匹配项的下标(内置函数或双指针)

  1. 找出字符串中第一个匹配项的下标
    给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack

的一部分,则返回 -1 。

示例 1:

输入:haystack = "sadbutsad", needle = "sad" 输出:0 解释:"sad" 在下标 0 和 6 处匹配。

第一个匹配项的下标是 0 ,所以返回 0 。 示例 2:

输入:haystack = "leetcode", needle = "leeto" 输出:-1 解释:"leeto" 没有在

"leetcode" 中出现,所以返回 -1 。

  • indexOf(String str, int index):
    返回从index位置开始查找指定字符str在字符串中第一次出现处的起始索引,如果此字符串中没有这样的字符,则返回 -1。
java 复制代码
class Solution {
    public int strStr(String haystack, String needle) {
        return haystack.indexOf(needle);
    }
}
  • 双指针解决
    思路:一个指针去遍历haystack,当遇到相等的时候,去依次遍历needle看看是否全部相等,如果没有的话,继续遍历haystack
java 复制代码
class Solution {
    public int strStr(String haystack, String needle) {
        if(needle=="") return -1;
         int hlength=haystack.length();
         int nlength=needle.length();
         int index=-1;
         for(int i=0;i<hlength;i++){
            if(hlength-i<nlength)
            break;
            if(haystack.charAt(i)==needle.charAt(0)){
                index=i;
                for(int j=1;j<nlength;j++){
                    i++;
                    if(needle.charAt(j)!=haystack.charAt(i))
                   { i=index;
                     index=-1;
                    break;
                   }

                }
                if(index!=-1)
                break;
            }

         }
         return index;
    }
}
相关推荐
九月十九12 分钟前
java使用aspose读取word里的图片
java·word
愚润求学15 分钟前
【递归、搜索与回溯】FloodFill算法(一)
c++·算法·leetcode
一 乐2 小时前
民宿|基于java的民宿推荐系统(源码+数据库+文档)
java·前端·数据库·vue.js·论文·源码
爱记录的小磊2 小时前
java-selenium自动化快速入门
java·selenium·自动化
鹏码纵横2 小时前
已解决:java.lang.ClassNotFoundException: com.mysql.jdbc.Driver 异常的正确解决方法,亲测有效!!!
java·python·mysql
weixin_985432112 小时前
Spring Boot 中的 @ConditionalOnBean 注解详解
java·spring boot·后端
Mr Aokey2 小时前
Java UDP套接字编程:高效实时通信的实战应用与核心类解析
java·java-ee
冬天vs不冷2 小时前
Java分层开发必知:PO、BO、DTO、VO、POJO概念详解
java·开发语言
sunny-ll2 小时前
【C++】详解vector二维数组的全部操作(超细图例解析!!!)
c语言·开发语言·c++·算法·面试