zoukankan      html  css  js  c++  java
  • 28. Implement strStr()

    题目链接:https://leetcode.com/problems/implement-strstr/

    解题思路:

    这其实是字符串匹配的问题,找到子串在字符串中出现的第一个位置,如果不存在返回-1。

    两层循环,第一层i循环是大的字符串,第二层j循环是小的字符串,如果两个匹配出现了不等的情况,那么这个i就要+1,跳出第二层循环。

    如果一直出现到j=n,说明小的字符串每一个位置都能在i中找到,那就返回当前指针i。

     1 class Solution {
     2     public int strStr(String haystack, String needle) {
     3         
     4         
     5         
     6         int m = haystack.length();
     7         int n = needle.length();
     8         
     9         if(n==0)
    10             return 0;
    11         if(n>m)
    12             return -1;
    13         
    14         for(int i=0;i<=m-n;i++)
    15         {
    16             int j=0;
    17             
    18             while(j<n)
    19             {
    20                 if(haystack.charAt(i+j)!=needle.charAt(j))
    21                     break;
    22                 j++;
    23             }
    24             if(j==n)
    25                 return i;
    26         }
    27         return -1;
    28     }
    29 }
  • 相关阅读:
    mysql事务
    mysql函数
    mysql自连接
    MYSQL添加外键关联
    SQL多表查询
    SQL数据完整性
    SQL limit
    SQL分组查询
    升级GCC 6.2编译LLVM的问题
    Quartz时SLF4J错误
  • 原文地址:https://www.cnblogs.com/wangyufeiaichiyu/p/10833627.html
Copyright © 2011-2022 走看看